/// <summary> /// Transforms a string containing a handlebars.js-compatible template into a template syntax tree /// </summary> /// <param name="templateText"></param> /// <param name="t"></param> /// <returns></returns> internal RootNode Parse(string templateText, Template t) { // Todo: rewrite this as a monadic parser combinator? // http://blogs.msdn.com/b/lukeh/archive/2007/08/19/monadic-parser-combinators-using-c-3-0.aspx // http://lorgonblog.wordpress.com/2007/12/02/c-3-0-lambda-and-the-first-post-of-a-series-about-monadic-parser-combinators/ // http://nblumhardt.com/2010/01/building-an-external-dsl-in-c/ (using sprache) try { // init context and rules var parserContext = new ParserContext(t); var textConsumer = new ParserTextConsumer(templateText); var rules = new ParserRules(parserContext); while (textConsumer.Consume()) { IRule rule = rules.Match(textConsumer.NextFragment); rule.ProcessContext(); } return parserContext.RootNode; } catch (Exception ex) { throw new Exception("An error occurred while parsing the provided template text:", ex); } }
/// <summary> /// Compiles a string into a Template object /// </summary> /// <param name="templateText"></param> /// <returns></returns> public static Template Compile(string templateText) { var template = new Template(); template._templateText = templateText; // set up some default helpers template._blockHelpers.Add("if", (h, c) => { return DefaultHelpers.If(h, c); }); template._blockHelpers.Add("else", (h, c) => { return DefaultHelpers.Else(h, c); }); template._blockHelpers.Add("with", (h, c) => { return DefaultHelpers.With(h, c); }); template._blockHelpers.Add("each", (h, c) => { return DefaultHelpers.Each(h, c); }); template._blockHelpers.Add("unless", (h, c) => { return DefaultHelpers.Unless(h, c); }); template.Parse(templateText); return template; }