Created
July 6, 2012 13:54
-
-
Save kylefritz/3060279 to your computer and use it in GitHub Desktop.
Compile Handlebars Templates in .net mvc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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