Syntax highlighting for script tags with html templates in Visual Studio 2010 MVC3 applications

With the prominence of frameworks like Knockout and Backbone, it is now quite common to use client side templates when working on client-side heavy web applications.

A convenient way to create client side templates has been to use the script tags like this:

<script id="templateId" type="text/html">
 <div>template contents</div>
</script>

However, VS2010 does not do syntax highlighting on script tags, which ends up looking ugly like this:


This has been a little annoyance to me and as a cure, I created a simple helper method influced by the Html.BeginForm() helper:

public static class HtmlHelperExtensions
{
    public static ScriptTag BeginHtmlTemplate(this HtmlHelper helper, string id)
    {
        return new ScriptTag(helper, "text/html", id);
    }
}

public class ScriptTag : IDisposable
{
    private readonly TextWriter writer;

    private readonly TagBuilder builder;

    public ScriptTag(HtmlHelper helper, string type, string id)
    {
        this.writer = helper.ViewContext.Writer;
        this.builder = new TagBuilder("script");
        this.builder.MergeAttribute("type", type);
        this.builder.MergeAttribute("id", id);
        writer.WriteLine(this.builder.ToString(TagRenderMode.StartTag));
    }

    public void Dispose()
    {
        writer.WriteLine(this.builder.ToString(TagRenderMode.EndTag));
    }
}

The helper can be used as follows:

@using (this.Html.BeginHtmlTemplate("person-template"))
{
   <h3></h3>
   <p>Credits: <span></span></p>
}

Here is the result, syntax highlighted:

5 thoughts on “Syntax highlighting for script tags with html templates in Visual Studio 2010 MVC3 applications

Leave a comment