Skip to content

Instantly share code, notes, and snippets.

@kylefritz
Created July 6, 2012 13:54
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kylefritz/3060279 to your computer and use it in GitHub Desktop.
Save kylefritz/3060279 to your computer and use it in GitHub Desktop.
Compile Handlebars Templates in .net mvc
using System.IO;
using System.Text;
using System.Web;
using System.Web.Optimization;
using Jurassic;
using System.Globalization;
namespace Fewt.Web
{
public class HandlebarsBundleTransform : IBundleTransform
{
ScriptEngine _scriptEngine;
bool _includeRuntime;
public HandlebarsBundleTransform(bool includeRuntime = true)
{
_includeRuntime = includeRuntime;
_scriptEngine = new ScriptEngine();
_scriptEngine.Execute(Properties.Resources.handlebars);
_scriptEngine.Execute("handlebarsPrecompile = Handlebars.precompile;");
}
//https://github.com/wycats/handlebars.js/blob/master/bin/handlebars
public void Process(BundleContext context, BundleResponse response)
{
var sb = new StringBuilder();
var usTextInfo = new CultureInfo("en-US", false).TextInfo;
if (_includeRuntime) sb.AppendLine(Properties.Resources.handlebars_runtime);
sb.AppendLine("(function() {\n var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};\n");
foreach (var assetFile in response.Files)
{
var template = File.ReadAllText(assetFile.FullName);
var compiled = _scriptEngine.CallGlobalFunction<string>("handlebarsPrecompile", template);
var templateName = Path.GetFileNameWithoutExtension(assetFile.FullName);
//convert template_name to TemplateName
templateName = usTextInfo.ToTitleCase(templateName).Replace("_", "");
sb.AppendLine("templates[\'" + templateName + "\'] = template(" + compiled + ");\n");
}
sb.AppendLine("})();");
response.Content = sb.ToString();
response.ContentType = "text/javascript";
response.Cacheability = HttpCacheability.Public;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment