Search code examples
c#stringtemplate-4

How to Html escape template fields


There's a few posts including this regarding Html escaping but this is not working for me. If I have a simple template such as this:

<html><body>$field$</body></html>

I need only the field to be escaped, not the whole template. I've created a custom render which uses the System.Web.HttpUtility class to perform the escaping of strings:

class HtmlRenderer : IAttributeRenderer
{
    public string ToString(object obj, string formatString, System.Globalization.CultureInfo culture)
    {
        return HttpUtility.HtmlEncode(
            new StringRenderer().ToString(obj, formatString, culture));
    }
}

And some sample code to render the template with some data:

public static string Render()
{
    var group = new TemplateGroup('$', '$');
    group.RegisterRenderer(typeof(string), new HtmlRenderer());
    var template = new Template(group, "<html><body>$field$</body></html>");
    template.Add("field", "Chalk & Cheese");
    return template.Render();
}

Returns the following:

&lt;html&gt;&lt;body&gt;Chalk &amp; Cheese&lt;/body&gt;&lt;/html&gt;

which escapes everything.

How can I escape only the fields added to the template?


Solution

  • I am new to stringtemplate but I think I have an idea on how to make it work, I think you are nearly there, whats missing is the format option in your stringtemplate. I think what you need is this:

    <html><body>$field;format="htmlTag"$</body></html>
    

    After tagging the string template with the "htmlTag" you can register a renderer, like the one you have done above and check for that tag as follows:

    public class HtmlRenderer:IAttributeRenderer
    {
        public string ToString(object obj,string formatString,CultureInfo culture)
        {
            if(formatString=="htmlEncode")
            { return HttpUtility.HtmlEncode(obj.ToString()); }
            return obj.ToString();
        }
    }
    

    More information can be found here: http://www.antlr.org/wiki/display/ST/Object+rendering

    Note: This is untested and my C# is not very good :) but I hope I have pointed you to the right direction.