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:
brilliant, this has been annoying me for weeks – lovely solution, thanks……..
This is a really good solution. I used it to answer a question on StackOverflow here: http://stackoverflow.com/questions/14449312/javascript-html-template-syntax-highlighting
Any chance you can do this in WebForms?
Aha — same idea — make a public method on the page like `ClientTemplateBegin(string attrId, string attrType = “text/html”)` and just return the generated script tags as strings…
Sorry, not really working with this stuff anymore! You’d think they would have fixed this in VS by now.