jehugaleahsa / mustache-sharp

An extension of the mustache text template engine for .NET.
The Unlicense
306 stars 80 forks source link

Escaping string for json templating #80

Closed TechWatching closed 7 years ago

TechWatching commented 7 years ago

I am using Mustache-sharp for json templating : it suits perfectly my needs however it does not escape strings (quotes and newlines in strings for instance). So when my data contains quotes, newlines or other special characters that need to be escaped, the resulting json does not have a correct format. How could I do json templating without having to create a custom tag to escape strings ?

jehugaleahsa commented 7 years ago

The Compile method will return a Generator, which has a KeyFound event you can attach to. There is a Substitute object on the KeyFoundEventHandler, which you can use to escape the value before it gets injected into the output:

var compiler = new FormatCompiler();
var generator = compiler.Compile("{{value}}");
generator.KeyFound += (sender, e) =>
{
    if (e.Key == "value" && e.Substitute is String)
    {
        string unescaped = (string)e.Substitute;
        e.Substitute = unescaped.Replace("\"", "\\\"");
    }
};
TechWatching commented 7 years ago

Thanks, it is exactly what I was looking for.