public HandlebarsCompiler(HandlebarsConfiguration configuration) { _configuration = configuration; _tokenizer = new Tokenizer(configuration); _expressionBuilder = new ExpressionBuilder(configuration); _functionBuilder = new FunctionBuilder(configuration); }
public HandlebarsCompiler(HandlebarsConfiguration configuration) { _configuration=configuration; _tokenizer = new Tokenizer(configuration); _expressionBuilder = new ExpressionBuilder(configuration); _functionBuilder = new FunctionBuilder(configuration); }
private static void InvokePartial( string partialName, BindingContext context, HandlebarsConfiguration configuration) { if (configuration.RegisteredTemplates.ContainsKey(partialName) == false) { if (configuration.FileSystem != null && context.TemplatePath != null) { var partialPath = configuration.FileSystem.Closest(context.TemplatePath, "partials/" + partialName + ".hbs"); if (partialPath != null) { var compiled = Handlebars.Create(configuration) .CompileView(partialPath); configuration.RegisteredTemplates.Add(partialName, (writer, o) => { writer.Write(compiled(o)); }); } } else { throw new HandlebarsRuntimeException( string.Format("Referenced partial name {0} could not be resolved", partialName)); } } configuration.RegisteredTemplates[partialName](context.TextWriter, context); }
private static bool InvokePartial( string partialName, BindingContext context, HandlebarsConfiguration configuration) { if (!configuration.TemplateRegistration.TryGetTemplate(partialName, out HandlebarsTemplate template)) { var partialLookupKey = $"{context.TemplateName ?? string.Empty}+{partialName}"; if (!configuration.TemplateRegistration.TryGetTemplate(partialLookupKey, out template)) { template = Handlebars.Create(configuration).CompileView(partialName, context.TemplateName, false); if (template == null) { return(false); } configuration.TemplateRegistration.RegisterTemplate(partialLookupKey, template); } else { return(false); } } try { template.RenderTo(context.TextWriter, context); return(true); } catch (Exception exception) { throw new HandlebarsRuntimeException( $"Runtime error while rendering partial '{partialName}', see inner exception for more information", exception); } }
private static void RegisterHelpers(this HandlebarsConfiguration handlebarsConfiguration, IEnumerable <IHelperBase> helpers) { foreach (var h in helpers) { h.Setup(handlebarsConfiguration); } }
private static bool InvokePartial( string partialName, BindingContext context, HandlebarsConfiguration configuration) { if (configuration.RegisteredTemplates.ContainsKey(partialName) == false) { if (configuration.FileSystem != null && context.TemplatePath != null) { var partialPath = configuration.FileSystem.Closest(context.TemplatePath, "partials/" + partialName + ".hbs"); if (partialPath != null) { var compiled = Handlebars.Create(configuration) .CompileView(partialPath); configuration.RegisteredTemplates.Add(partialName, (writer, o) => { writer.Write(compiled(o)); }); } else { // Failed to find partial in filesystem return(false); } } else { return(false); } } configuration.RegisteredTemplates[partialName](context.TextWriter, context); return(true); }
public void BasicPathNoThrowOnNullExpression() { var source = @"{{#if foo}} {{foo.bar}} {{else}} false {{/if}} "; var config = new HandlebarsConfiguration { ThrowOnUnresolvedBindingExpression = true }; var handlebars = Handlebars.Create(config); var template = handlebars.Compile(source); var data = new { foo = (string)null }; var result = template(data); Assert.Contains("false", result); }
private static bool IsBlockHelper(Expression item, HandlebarsConfiguration configuration) { item = UnwrapStatement(item); var helperExpression = item as HelperExpression; return(helperExpression != null && configuration.BlockHelpers.ContainsKey(helperExpression.HelperName.Replace("#", ""))); }
public static ObjectEnumeratorValueProvider Create(HandlebarsConfiguration configuration) { var provider = Pool.Get(); provider._configuration = configuration; return(provider); }
public void CanRenderCasparIndexTemplate() { var configuration = new HandlebarsConfiguration { TemplateContentProvider = new DiskFileSystemTemplateContentProvider() }; var handlebars = Handlebars.Create(configuration); AddHelpers(handlebars); var renderView = handlebars.CompileView("Providers/Casper-master/index.hbs"); var output = renderView.Render(new { blog = new { url = "http://someblog.com", title = "This is the blog title" }, posts = new[] { new { title = "My Post Title", image = "/someimage.png", post_class = "somepostclass" } } }); var cq = CsQuery.CQ.CreateDocument(output); Assert.Equal("My Post Title", cq["h2.post-title a"].Text()); }
public void CanIterateOverDictionaryInLayout() { var files = new FakeFileSystem { { "views\\layout.hbs", "Layout: {{#each this}}{{#if @First}}First:{{/if}}{{#if @Last}}Last:{{/if}}{{@Key}}={{@Value}};{{/each}}{{{body}}}" }, { "views\\someview.hbs", "{{!< layout}} View" }, }; var handlebarsConfiguration = new HandlebarsConfiguration { FileSystem = files, }; var handlebars = Handlebars.Create(handlebarsConfiguration); var render = handlebars.CompileView("views\\someview.hbs"); var output = render( new Dictionary <string, object> { { "Foo", "Bar" }, { "Baz", "Foo" }, { "Bar", "Baz" }, } ); Assert.Equal("Layout: First:Foo=Bar;Baz=Foo;Last:Bar=Baz; View", output); }
public void CanIterateOverObjectInLayout() { var files = new FakeFileSystem { { "views\\layout.hbs", "Layout: {{#each this}}{{#if @First}}First:{{/if}}{{#if @Last}}Last:{{/if}}{{@Key}}={{@Value}};{{/each}}{{{body}}}" }, { "views\\someview.hbs", "{{!< layout}} View" }, }; var handlebarsConfiguration = new HandlebarsConfiguration { FileSystem = files, Compatibility = { SupportLastInObjectIterations = true, }, }; var handlebars = Handlebars.Create(handlebarsConfiguration); var render = handlebars.CompileView("views\\someview.hbs"); var output = render( new { Foo = "Bar", Baz = "Foo", Bar = "Baz", } ); Assert.Equal("Layout: First:Foo=Bar;Baz=Foo;Last:Bar=Baz; View", output); }
public void AssertHandlebarsUndefinedBindingException() { var source = "Hello, {{person.firstname}} {{person.lastname}}!"; var config = new HandlebarsConfiguration { ThrowOnUnresolvedBindingExpression = true }; var handlebars = Handlebars.Create(config); var template = handlebars.Compile(source); var data = new { person = new { firstname = "Erik" } }; try { template(data); } catch (HandlebarsUndefinedBindingException ex) { Assert.Equal("person.lastname", ex.Path); Assert.Equal("lastname", ex.MissingKey); return; } Assert.False(true, "Exception is expected."); }
public static BlockAccumulatorContext Create(Expression item, HandlebarsConfiguration configuration) { BlockAccumulatorContext context = null; if (IsConditionalBlock(item)) { context = new ConditionalBlockAccumulatorContext(item); } else if (IsPartialBlock(item)) { context = new PartialBlockAccumulatorContext(item); } else if (IsBlockHelper(item, configuration)) { context = new BlockHelperAccumulatorContext(item); } else if (IsIteratorBlock(item)) { context = new IteratorBlockAccumulatorContext(item); } else if (IsDeferredBlock(item)) { context = new DeferredBlockAccumulatorContext(item); } return context; }
public static BlockAccumulatorContext Create(Expression item, HandlebarsConfiguration configuration) { BlockAccumulatorContext context = null; if (IsConditionalBlock(item)) { context = new ConditionalBlockAccumulatorContext(item); } else if (IsPartialBlock(item)) { context = new PartialBlockAccumulatorContext(item); } else if (IsBlockHelper(item, configuration)) { context = new BlockHelperAccumulatorContext(item); } else if (IsIteratorBlock(item)) { context = new IteratorBlockAccumulatorContext(item); } else if (IsDeferredBlock(item)) { context = new DeferredBlockAccumulatorContext(item); } return(context); }
public override void Setup(HandlebarsConfiguration configuration) { configuration.Helpers.Add("set", SetHelper); configuration.Helpers.Add("get", GetHelper); configuration.Helpers.Add("clear", ClearHelper); configuration.BlockHelpers.Add("with_get", WithGetHelper); configuration.BlockHelpers.Add("with_set", WithSetHelper); }
/// <summary> /// Adds <c>log</c> helper that uses provided <paramref name="loggerFactory"/> /// </summary> /// <param name="configuration"></param> /// <param name="loggerFactory"></param> /// <returns></returns> public static HandlebarsConfiguration UseLogger(this HandlebarsConfiguration configuration, ILoggerFactory loggerFactory) { var compileTimeConfiguration = configuration.CompileTimeConfiguration; compileTimeConfiguration.Features.Add(new LoggerFeatureFactory(loggerFactory)); return(configuration); }
private static HandlebarsConfiguration GetHandleBarsConfiguration(IPartialTemplateResolver templateResolver, IEnumerable <IHelperBase> moreHelpers) { var configuration = new HandlebarsConfiguration(); configuration.RegisterDefaultHelpers(); configuration.RegisterHelpers(moreHelpers); configuration.PartialTemplateResolver = templateResolver; return(configuration); }
public CustomConfigurationTests() { var configuration = new HandlebarsConfiguration { ExpressionNameResolver = new UpperCamelCaseExpressionNameResolver() }; HandlebarsInstance = Handlebars.Create(configuration); }
/// <summary> /// Adds <see cref="IObjectDescriptorProvider"/>s required to support <c>System.Text.Json</c>. /// </summary> /// <param name="configuration"></param> /// <returns></returns> public static HandlebarsConfiguration UseJson(this HandlebarsConfiguration configuration) { var providers = configuration.ObjectDescriptorProviders; providers.Add(JsonDocumentObjectDescriptor); providers.Add(JsonElementObjectDescriptor); return(configuration); }
public void Init() { var configuration = new HandlebarsConfiguration { ExpressionNameResolver = new UpperCamelCaseExpressionNameResolver() }; this.HandlebarsInstance = Handlebars.Create(configuration); }
/// <summary> /// Allows to warm-up internal caches for specific types /// </summary> public static HandlebarsConfiguration UseWarmUp(this HandlebarsConfiguration configuration, Action <ICollection <Type> > configure) { var types = new HashSet <Type>(); configure(types); configuration.CompileTimeConfiguration.Features.Add(new WarmUpFeatureFactory(types)); return(configuration); }
public FileBasedHandlebarsTemplateEngine(string templateDirectoryPath) { BasePath = templateDirectoryPath ?? throw new ArgumentNullException(nameof(templateDirectoryPath)); Configuration = new HandlebarsConfiguration() { ThrowOnUnresolvedBindingExpression = true }; Handlebars = HandlebarsDotNet.Handlebars.Create(Configuration); }
private static void InvokePartial( string partialName, BindingContext context, HandlebarsConfiguration configuration) { if (configuration.RegisteredTemplates.ContainsKey(partialName) == false) { throw new HandlebarsRuntimeException("Referenced partial name could not be resolved"); } configuration.RegisteredTemplates[partialName](context.TextWriter, context); }
public TemplateCollection() { var config = new HandlebarsConfiguration { // Not yet available. Uncomment later. //ThrowOnUnresolvedBindingExpression = true, TextEncoder = new NoopTextEncoder() }; this.Instance = Handlebars.Create(config); }
/// <summary> /// Allows to intercept calls to missing helpers. /// <para>For Handlebarsjs docs see: https://handlebarsjs.com/guide/hooks.html#helpermissing</para> /// </summary> /// <param name="configuration"></param> /// <param name="helperMissing">Delegate that returns interceptor for <see cref="HandlebarsReturnHelper"/> and <see cref="HandlebarsHelper"/></param> /// <param name="blockHelperMissing">Delegate that returns interceptor for <see cref="HandlebarsBlockHelper"/></param> /// <returns></returns> public static HandlebarsConfiguration RegisterMissingHelperHook( this HandlebarsConfiguration configuration, HandlebarsReturnWithOptionsHelper helperMissing = null, HandlebarsBlockHelper blockHelperMissing = null ) { return(configuration.RegisterMissingHelperHook( helperMissing != null ? new DelegateReturnHelperWithOptionsDescriptor("helperMissing", helperMissing) : null, blockHelperMissing != null ? new DelegateBlockHelperDescriptor("blockHelperMissing", blockHelperMissing) : null )); }
private static void InvokePartial( string partialName, BindingContext context, HandlebarsConfiguration configuration) { if(configuration.RegisteredTemplates.ContainsKey(partialName) == false) { throw new HandlebarsRuntimeException("Referenced partial name could not be resolved"); } configuration.RegisteredTemplates[partialName](context.TextWriter, context); }
private static bool IsBlockHelper(Expression item, HandlebarsConfiguration configuration) { item = UnwrapStatement(item); if (item is HelperExpression hitem) { var helperName = hitem.HelperName; return(!configuration.Helpers.ContainsKey(helperName) && configuration.BlockHelpers.ContainsKey(helperName.Replace("#", ""))); } return(false); }
public static string GetHelperResultFromJToken(IHelper helper, string json, string template) { var configuration = new HandlebarsConfiguration(); helper.Setup(configuration); var handleBar = Handlebars.Create(configuration); var hb = handleBar.Compile(template); var output = hb.Invoke(JToken.Parse(json)); return(output); }
private static string GenerateFileContent(Student student) { var formatCustomHelper = new FormatCustomHelper(); var config = new HandlebarsConfiguration(); config.Helpers.Add(formatCustomHelper.Key, formatCustomHelper.Write); string fileTemplate = File.ReadAllText("OutboundStudent.hbs"); var template = Handlebars.Create(config).Compile(fileTemplate); var result = template(student); return(result); }
public void BasicLogging() { var loggerMock = new Mock <ILogger>(); var configuration = new HandlebarsConfiguration { Logger = loggerMock.Object }; var engine = new HandlebarsEngine(configuration); var template = engine.Compile("{{log \"Look at me!\"}}"); template.Render(null); loggerMock.Verify(l => l.Log("Look at me!", LogLevel.Info)); }
/// <summary> /// Changes <see cref="IExpressionCompiler"/> to the one using <c>FastExpressionCompiler</c> /// </summary> /// <param name="configuration"></param> /// <returns></returns> public static HandlebarsConfiguration UseCompileFast(this HandlebarsConfiguration configuration) { if (!OperatingSystem.IsWindows()) { Debug.WriteLine("[WARNING] Only Windows OS is supported at the moment. Skipping feature."); return(configuration); } var compileTimeConfiguration = configuration.CompileTimeConfiguration; compileTimeConfiguration.Features.Add(new FastCompilerFeatureFactory()); return(configuration); }
public void EverythingAfterLogLevelIsNotLogged() { var loggerMock = new Mock <ILogger>(); var configuration = new HandlebarsConfiguration { Logger = loggerMock.Object }; var engine = new HandlebarsEngine(configuration); var template = engine.Compile("{{log \"Logged!\" level=\"error\" \"Not logged!\" }}"); template.Render(null); loggerMock.Verify(l => l.Log("Logged!", LogLevel.Error)); loggerMock.Verify(l => l.Log("Not logged!", It.IsAny <LogLevel>()), Times.Never); }
public void NoOutputEncoding() { var template = "Hello {{person.name}} {{person.surname}} from {{person.address.homeCountry}}. You're {{description}}."; var configuration = new HandlebarsConfiguration { TextEncoder = null }; var handlebarsInstance = Handlebars.Create(configuration); var output = handlebarsInstance.Compile(template).Invoke(Value); Assert.AreEqual(ExpectedOutput, output); }
private static bool InvokePartial( string partialName, BindingContext context, HandlebarsConfiguration configuration) { if (configuration.RegisteredTemplates.ContainsKey(partialName) == false) { if (configuration.FileSystem != null && context.TemplatePath != null) { var partialPath = configuration.FileSystem.Closest(context.TemplatePath, "partials/" + partialName + ".hbs"); if (partialPath != null) { var compiled = Handlebars.Create(configuration) .CompileView(partialPath); configuration.RegisteredTemplates.Add(partialName, (writer, o) => { writer.Write(compiled(o)); }); } else { // Failed to find partial in filesystem return false; } } else { return false; } } try { configuration.RegisteredTemplates[partialName]( context.TextWriter, context ); return true; } catch ( Exception exception ) { throw new HandlebarsRuntimeException( $"Runtime error while rendering partial '{partialName}', see inner exception for more information", exception ); } }
private static void RegisterHandlebarsViewEngine() { ViewEngines.Engines.Clear(); var config = new HandlebarsConfiguration() { FileSystem = new HandlebarsMvcViewEngineFileSystem(), }; var handlebars = Handlebars.Create(config); /* Helpers need to be registered up front - these are dummmy implementations of the ones used in Ghost*/ handlebars.RegisterHelper("asset", (writer, context, arguments) => writer.Write("asset:" + string.Join("|", arguments))); handlebars.RegisterHelper("date", (writer, context, arguments) => writer.Write("date:" + string.Join("|", arguments))); handlebars.RegisterHelper("tags", (writer, context, arguments) => writer.Write("tags:" + string.Join("|", arguments))); handlebars.RegisterHelper("encode", (writer, context, arguments) => writer.Write("encode:" + string.Join("|", arguments))); handlebars.RegisterHelper("url", (writer, context, arguments) => writer.Write("url:" + string.Join("|", arguments))); ViewEngines.Engines.Add(new HandlebarsMvcViewEngine(handlebars)); }
public void CanRenderCasparPostNoLayoutTemplate() { var fs = (new DiskFileSystem()); var handlebarsConfiguration = new HandlebarsConfiguration() {FileSystem = fs}; var handlebars = Handlebars.Create(handlebarsConfiguration); AddHelpers(handlebars); var renderView = handlebars.CompileView("ViewEngine/Casper-master/post-no-layout.hbs"); var output = renderView(new { post = new { title = "My Post Title", image = "/someimage.png", post_class = "somepostclass" } }); var cq = CsQuery.CQ.CreateDocument(output); Assert.AreEqual("My Post Title", cq["h1.post-title"].Html()); }
public FunctionBuilder(HandlebarsConfiguration configuration) { _configuration = configuration; }
public void JsonEncoding() { var template = "No html entities, {{Username}}."; var configuration = new HandlebarsConfiguration { TextEncoder = new JsonEncoder() }; var handlebarsInstance = Handlebars.Create(configuration); var value = new {Username = "******"<Eric>\"\n<Sharp>"}; var output = handlebarsInstance.Compile(template).Invoke(value); Assert.AreEqual(@"No html entities, \""<Eric>\""\n<Sharp>.", output); }
public CompilationContext(HandlebarsConfiguration configuration) { _configuration = configuration; _bindingContext = Expression.Variable(typeof(BindingContext), "context"); }
public static IEnumerable<object> Convert( IEnumerable<object> sequence, HandlebarsConfiguration configuration) { return new HelperConverter(configuration).ConvertTokens(sequence).ToList(); }
private BlockAccumulator(HandlebarsConfiguration configuration) { _configuration = configuration; }
public static IEnumerable<object> Remove(IEnumerable<object> sequence, HandlebarsConfiguration configuration) { return new WhitespaceRemover(configuration).ConvertTokens(sequence).ToList(); }
private WhitespaceRemover(HandlebarsConfiguration configuration) { _configuration = configuration; }
private static bool IsBlockHelper(Expression item, HandlebarsConfiguration configuration) { item = UnwrapStatement(item); return (item is HelperExpression) && configuration.BlockHelpers.ContainsKey(((HelperExpression)item).HelperName.Replace("#", "")); }
public UndefinedBindingResult(string value, HandlebarsConfiguration configuration) { Value = value; _configuration = configuration; }
public ExpressionBuilder(HandlebarsConfiguration configuration) { _configuration = configuration; }
private HelperConverter(HandlebarsConfiguration configuration) { _configuration = configuration; }
//TODO: structure parser public Tokenizer(HandlebarsConfiguration configuration) { _configuration = configuration; }
public static IEnumerable<object> Accumulate( IEnumerable<object> tokens, HandlebarsConfiguration configuration) { return new BlockAccumulator(configuration).ConvertTokens(tokens).ToList(); }