Skip to content

Instantly share code, notes, and snippets.

@alfeg
Created October 13, 2011 11:02
Show Gist options
  • Save alfeg/1283974 to your computer and use it in GitHub Desktop.
Save alfeg/1283974 to your computer and use it in GitHub Desktop.
Html helper for script jquery templates
public static class GenericHelpers
{
public static HtmlTemplate HtmlTemplate(this HtmlHelper html, object htmlAttributes)
{
return new HtmlTemplate(html, htmlAttributes);
}
}
@using (Html.HtmlTemplate(new { id = "someTemplate" }))
{
<span>${ someTemplateField }</span>
}
public class HtmlTemplate : IDisposable
{
private bool disposed;
private readonly TagBuilder tagBuilder;
private readonly TextWriter textWriter;
public HtmlTemplate(HtmlHelper html, object htmlAttributes)
{
this.textWriter = html.ViewContext.Writer;
this.tagBuilder = new TagBuilder("script");
this.tagBuilder.MergeAttribute("type", "text/x-jquery-tmpl");
this.tagBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
this.textWriter.Write(this.tagBuilder.ToString(TagRenderMode.StartTag));
}
public void Dispose()
{
Dispose(true /* disposing */);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
this.disposed = true;
textWriter.Write(tagBuilder.ToString(TagRenderMode.EndTag));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment