public void DefineSection_can_append()
            {
                var hbsve = new HandlebarsViewEngine();

                hbsve.RegisterSectionsHelpers();
                var handlebars = Handlebars.Create(hbsve.HandlebarsConfiguration);

                var view    = new CompiledView(handlebars.Compile("{{#definesection \"name\"}}From view.{{/definesection}}"), null, null);
                var layout1 = new CompiledView(handlebars.Compile("{{#definesection \"name\" mode=\"append\"}}Appended.{{/definesection}}"), null, null);
                var layout2 = new CompiledView(handlebars.Compile("{{rendersection \"name\"}}"), null, null);

                var controllerContext = new ControllerContext();
                var hbsview           = new HandlebarsView(controllerContext, view, new[] { layout1, layout2 });

                var html = GetHtmlFromView(hbsview);

                Assert.Equal("From view.Appended.", html);
            }
            public void RenderSection_throws_for_undefined_section_when_required()
            {
                var hbsve = new HandlebarsViewEngine();

                hbsve.RegisterSectionsHelpers();
                var handlebars = Handlebars.Create(hbsve.HandlebarsConfiguration);

                var view   = new CompiledView(handlebars.Compile("Body not rendered."), null, null);
                var layout = new CompiledView(handlebars.Compile("Name: {{rendersection \"name\"}}."), null, null);

                var controllerContext = new ControllerContext();
                var hbsview           = new HandlebarsView(controllerContext, view, new[] { layout });

                Assert.Throws <HelperException>(() =>
                {
                    var html = GetHtmlFromView(hbsview);
                });
            }
示例#3
0
        public void WithCategoryPrefixAndExtraWithPrefix()
        {
            // Arrange
            var handlebarsContext = Handlebars.Create();

            HandlebarsHelpers.Register(handlebarsContext, options =>
            {
                options.UseCategoryPrefix = true;
                options.Prefix            = "test";
            });
            var action = handlebarsContext.Compile("{{[test.String.Append] \"foo\" \"bar\"}}");

            // Act
            var result = action("");

            // Assert
            result.Should().Be("foobar");
        }
示例#4
0
        public void BasicPathUnresolvedBindingFormatter()
        {
            var source = "Hello, {{foo}}!";

            var config = new HandlebarsConfiguration
            {
                UnresolvedBindingFormatter = "('{0}' is undefined)"
            };
            var handlebars = Handlebars.Create(config);

            var template = handlebars.Compile(source);
            var data     = new {
                name = "Handlebars.Net"
            };
            var result = template(data);

            Assert.Equal("Hello, ('foo' is undefined)!", result);
        }
        public void BasicIterator()
        {
            var source   = "Hello,{{#each people}}\n- {{name}}{{/each}}";
            var template = Handlebars.Create().Compile(source);
            var data     = new {
                people = new [] {
                    new {
                        name = "Erik"
                    },
                    new {
                        name = "Helen"
                    }
                }
            };
            var result = template(data);

            Assert.Equal("Hello,\n- Erik\n- Helen", result);
        }
示例#6
0
        public void BasicPathThrowOnUnresolvedBindingExpression()
        {
            var source = "Hello, {{foo}}!";

            var config = new HandlebarsConfiguration
            {
                ThrowOnUnresolvedBindingExpression = true
            };
            var handlebars = Handlebars.Create(config);
            var template   = handlebars.Compile(source);

            var data = new
            {
                name = "Handlebars.Net"
            };

            Assert.Throws <HandlebarsUndefinedBindingException>(() => template(data));
        }
示例#7
0
        public MainForm()
        {
            InitializeComponent();

            _InventoryManager = new InventoryManager();
            _MixModel         = new MixModel();

            var handlebarsConfig = new HandlebarsConfiguration();

            handlebarsConfig.Helpers.Add("percent", (output, context, arguments) => output.Write(string.Format("{0:P}", arguments)));
            handlebarsConfig.Helpers.Add("unit", (output, context, arguments) => output.Write(string.Format("{0} {1}", arguments)));
            _Handlebars = Handlebars.Create(handlebarsConfig);

            tabPageEntryBindingSource.DataSource = new List <TabPageEntry>
            {
                new TabPageEntry(R.mix, R.TabMix),
                new TabPageEntry(R.recipes, R.TabRecipes),
                new TabPageEntry(R.ingredients, R.TabIngredients)
            };

            _InventoryManager.PropertyChanged += OnInventoryManagerPropertyChanged;

            if (!string.IsNullOrEmpty(Settings.Default.LastInventoryFile))
            {
                _InventoryManager.Load(Settings.Default.LastInventoryFile);
            }
            else
            {
                _InventoryManager.New("new_inventory.xml");
            }

            numMixVolume.DataBindings.Add(nameof(NumericUpDown.Value), _MixModel, nameof(MixModel.Volume), false, DataSourceUpdateMode.OnPropertyChanged);
            numMixNicotine.DataBindings.Add(nameof(NumericUpDown.Value), _MixModel, nameof(MixModel.NicotineDose), false, DataSourceUpdateMode.OnPropertyChanged);
            numMixVg.DataBindings.Add(nameof(NumericUpDown.Value), _MixModel, nameof(MixModel.VgPercentage), false, DataSourceUpdateMode.OnPropertyChanged);
            numMixPg.DataBindings.Add(nameof(NumericUpDown.Value), _MixModel, nameof(MixModel.PgPercentage), false, DataSourceUpdateMode.OnPropertyChanged);
            _MixModel.PropertyChanged += OnMixModelPropertyChanged;
            mixIngredientModelBindingSource.DataSource = _MixModel.Ingredients;
            SetErrors();

            cmbRecipeIngredientAdd.ComboBox.DataSource = ingredientBindingSource;

            SetTitle();
            saveInventoryToolStripMenuItem.Enabled = _InventoryManager.IsDirty;
        }
        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);
            }
        }
示例#9
0
        private static bool InvokePartial(
            string partialName,
            BindingContext context,
            HandlebarsConfiguration configuration)
        {
            if (partialName.Equals(SpecialPartialBlockName))
            {
                if (context.PartialBlockTemplate == null)
                {
                    return(false);
                }

                context.PartialBlockTemplate(context.TextWriter, context);
                return(true);
            }

            //if we have an inline partial, skip the file system and RegisteredTemplates collection
            if (context.InlinePartialTemplates.ContainsKey(partialName))
            {
                context.InlinePartialTemplates[partialName](context.TextWriter, context);
                return(true);
            }

            // Partial is not found, so call the resolver and attempt to load it.
            if (!configuration.RegisteredTemplates.ContainsKey(partialName))
            {
                if (configuration.PartialTemplateResolver == null ||
                    !configuration.PartialTemplateResolver.TryRegisterPartial(Handlebars.Create(configuration), partialName, context.TemplatePath))
                {
                    // Template not found.
                    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);
            }
        }
示例#10
0
        public void HelperEscapedLateBound(string helperName)
        {
            var handlebars = Handlebars.Create();

            var source = "{{" + helperName + "}}";

            var template = handlebars.Compile(source);

            var expected = "late";

            handlebars.RegisterHelper(helperName.Trim('[', ']'), (writer, context, arguments) =>
            {
                writer.WriteSafeString(expected);
            });

            var output = template(null);

            Assert.Equal(expected, output);
        }
示例#11
0
        public void BasicPathThrowOnNestedUnresolvedBindingExpression()
        {
            var source = "Hello, {{foo.bar}}!";

            var config = new HandlebarsConfiguration
            {
                ThrowOnUnresolvedBindingExpression = true
            };
            var handlebars = Handlebars.Create(config);
            var template   = handlebars.Compile(source);

            var data = new
            {
                foo = (object)null
            };
            var ex = Assert.Throws <HandlebarsUndefinedBindingException>(() => template(data));

            Assert.Equal("bar is undefined", ex.Message);
        }
示例#12
0
        public void BasicSubExpressionWithPathArgument()
        {
            var handlebars = Handlebars.Create();

            handlebars.RegisterHelper("helper", (writer, context, args) => writer.Write($"Outer {args[0]}"));
            handlebars.RegisterHelper("subhelper", (writer, context, args) => writer.Write($"Inner {args[0]}"));

            var source = "{{helper (subhelper property)}}";

            var template = handlebars.Compile(source);

            var output = template(new {
                property = "inner-arg"
            });

            var expected = "Outer Inner inner-arg";

            Assert.Equal(expected, output);
        }
示例#13
0
        public void RawHelperShouldNotMangleArgumentsInBodyIfAnExistingHelperIsReferenced()
        {
            var inst   = Handlebars.Create();
            var source = "{{{{rawBlockHelper}}}}{{someHelper fooArg fooHashArg='foo' fooHashArgDoubleQuote=\"foo!\" barHashArg=unquotedValue [email protected]}}{{{{/rawBlockHelper}}}}";

            inst.RegisterHelper("rawBlockHelper", (writer, options, context, arguments) => {
                options.Template(writer, null);
            });

            inst.RegisterHelper("someHelper", (writer, context, parameters) =>
            {
                throw new Exception("If this gets called, something went terribly wrong.");
            });

            var template = inst.Compile(source);
            var output   = template(new { });

            Assert.Equal("{{someHelper fooArg fooHashArg='foo' fooHashArgDoubleQuote=\"foo!\" barHashArg=unquotedValue [email protected]}}", output);
        }
示例#14
0
        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));
        }
示例#15
0
        public void CanIterateOverEnumerableInLayout()
        {
            var files = new FakeFileSystem
            {
                { "views\\layout.hbs", "Layout: {{#each this}}{{#if @First}}First:{{/if}}{{#if @Last}}Last:{{/if}}{{this}};{{/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(
                Enumerable.Range(0, 5)
                );

            Assert.Equal("Layout: First:0;1;2;3;Last:4; View", output);
        }
示例#16
0
        public void CanRenderAGlobalVariable()
        {
            //Given a layout in the root which contains an @ variable
            var configuration = new HandlebarsConfiguration
            {
                TemplateContentProvider = new FakeFileSystemTemplateContentProvider
                {
                    { "views\\someview.hbs", "This is the {{@body.title}}" }
                }
            };

            //When a viewengine renders that view
            var handlebars = Handlebars.Create(configuration);
            var render     = handlebars.CompileView("views\\someview.hbs");
            var output     = render.Render(new { @body = new { title = "THING" } });

            //Then the correct output should be rendered
            Assert.Equal("This is the THING", output);
        }
示例#17
0
        public void StandalonePartials()
        {
            string source = "Here are:\n  {{>person}} \n {{>person}}  ";

            var handlebars = Handlebars.Create();
            var template   = handlebars.Compile(source);

            var data          = new { name = "Marc" };
            var partialSource = "{{name}}";

            using (var reader = new StringReader(partialSource))
            {
                var partialTemplate = handlebars.Compile(reader);
                handlebars.RegisterTemplate("person", partialTemplate);
            }

            var result = template(data);

            Assert.Equal("Here are:\nMarcMarc", result);
        }
        public void BasicPartial()
        {
            string source = "Hello, {{>person}}!";

            var handlebars = Handlebars.Create(new HandlebarsConfiguration
            {
                PartialTemplateResolver = new CustomPartialResolver()
            });


            var template = handlebars.Compile(source);

            var data = new {
                name = "Marc"
            };

            var result = template(data);

            Assert.Equal("Hello, Marc!", result);
        }
示例#19
0
        public void HtmlIsNotEscapedInsideRawHelper()
        {
            var inst   = Handlebars.Create();
            var source = "{{{{rawBlockHelper html}}}} {{ foo }} {{{{/rawBlockHelper}}}}";

            inst.RegisterHelper("rawBlockHelper", (writer, options, context, arguments) => {
                writer.Write(arguments[0]);
                options.Template(writer, null);
            });

            var data = new
            {
                html = "<div>foo</div>"
            };

            var template = inst.Compile(source);
            var output   = template(data);

            Assert.Equal("<div>foo</div> {{foo}} ", output);
        }
示例#20
0
        public void TestNestedPartials()
        {
            var innerPartial = @"{{#>outer-partial}}<br />
        Begin inner partial<br />
            Begin inner partial block<br />
                {{>@partial-block}}
            End  inner partial block<br />
        End inner partial<br />
        {{/outer-partial}}";

            var outerPartial = @"Begin outer partial<br />
            Begin outer partial block
                {{>@partial-block}}
            End outer partial block<br />
        End outer partial";

            var view = @"{{#>inner-partial}}
          View<br />
        {{/inner-partial}}";

            var handlebars = Handlebars.Create();

            handlebars.RegisterTemplate("outer-partial", outerPartial);
            handlebars.RegisterTemplate("inner-partial", innerPartial);

            var    callback = handlebars.Compile(view);
            string result   = callback(new object());

            const string expected = @"Begin outer partial<br />
            Begin outer partial block
<br />
        Begin inner partial<br />
            Begin inner partial block<br />
          View<br />
            End  inner partial block<br />
        End inner partial<br />
            End outer partial block<br />
        End outer partial";

            Assert.Equal(expected, result);
        }
示例#21
0
        public void RegisterBlockHelper()
        {
            var handlebars = Handlebars.Create();

            handlebars.RegisterHelper("StringEqualityBlockHelper", (output, options, context, arguments) =>
            {
                if (arguments.Length != 2)
                {
                    throw new HandlebarsException("{{#StringEqualityBlockHelper}} helper must have exactly two arguments");
                }

                var left  = arguments.At <string>(0);
                var right = arguments[1] as string;
                if (left == right)
                {
                    options.Template(output, context);
                }
                else
                {
                    options.Inverse(output, context);
                }
            });

            var animals = new Dictionary <string, string>
            {
                { "Fluffy", "cat" },
                { "Fido", "dog" },
                { "Chewy", "hamster" }
            };

            var    template         = "{{#each this}}The animal, {{@key}}, {{#StringEqualityBlockHelper @value 'dog'}}is a dog{{else}}is not a dog{{/StringEqualityBlockHelper}}.\r\n{{/each}}";
            var    compiledTemplate = handlebars.Compile(template);
            string templateOutput   = compiledTemplate(animals);

            Assert.Equal(
                "The animal, Fluffy, is not a dog.\r\n" +
                "The animal, Fido, is a dog.\r\n" +
                "The animal, Chewy, is not a dog.\r\n",
                templateOutput
                );
        }
示例#22
0
        public void CanLoadAViewWithALayoutWithAVariable()
        {
            //Given a layout in the root
            var files = new FakeFileSystem()
            {
                { "somelayout.hbs", "{{var1}} start\r\n{{{body}}}\r\n{{var1}} end" },
                //And a view in a subfolder folder which uses that layout
                { "views\\someview.hbs", "{{!< somelayout}}This is the {{var2}}" }
            };

            //When a viewengine renders that view
            var handleBars = Handlebars.Create(new HandlebarsConfiguration()
            {
                FileSystem = files
            });
            var renderView = handleBars.CompileView("views\\someview.hbs");
            var output     = renderView(new { var1 = "layout", var2 = "body" });

            //Then the correct output should be rendered
            Assert.Equal("layout start\r\nThis is the body\r\nlayout end", output);
        }
示例#23
0
        public void CanLoadAViewWithALayout()
        {
            //Given a layout in a subfolder
            var configuration = new HandlebarsConfiguration
            {
                TemplateContentProvider = new FakeFileSystemTemplateContentProvider
                {
                    { "views\\somelayout.hbs", "layout start\r\n{{{body}}}\r\nlayout end" },
                    //And a view in the same folder which uses that layout
                    { "views\\someview.hbs", "{{!< somelayout}}This is the body" }
                }
            };

            //When a viewengine renders that view
            var handleBars = Handlebars.Create(configuration);
            var renderView = handleBars.CompileView("views\\someview.hbs");
            var output     = renderView.Render(null);

            //Then the correct output should be rendered
            Assert.Equal("layout start\r\nThis is the body\r\nlayout end", output);
        }
示例#24
0
        public void MissingHelperHookViaFeatureAndMethod()
        {
            var expected   = "Hook";
            var handlebars = Handlebars.Create();

            handlebars.Configuration
            .RegisterMissingHelperHook(
                (context, arguments) => "Should be ignored"
                );

            handlebars.RegisterHelper("helperMissing",
                                      (context, arguments) => expected
                                      );

            var source   = "{{missing}}";
            var template = handlebars.Compile(source);

            var output = template(null);

            Assert.Equal(expected, output);
        }
示例#25
0
        public void NestedSubExpressionsWithNumericLiteralArguments()
        {
            var handlebars = Handlebars.Create();

            handlebars.RegisterHelper("write", (writer, context, args) => {
                writer.Write(args[0]);
            });

            handlebars.RegisterHelper("add", (context, args)
                                      => args.At <int>(0) + args.At <int>(1));

            var source = "{{write (add (add 1 2) 3 )}}";

            var template = handlebars.Compile(source);

            var output = template(new { });

            var expected = "6";

            Assert.Equal(expected, output);
        }
示例#26
0
        public void MissingBlockHelperHookViaHelperRegistration(string helperName)
        {
            var handlebars = Handlebars.Create();
            var format     = "Missing block helper: {0}";

            handlebars.RegisterHelper("blockHelperMissing", (writer, options, context, arguments) =>
            {
                var name = options.GetValue <string>("name");
                writer.WriteSafeString(string.Format(format, name.Trim('[', ']')));
            });

            var source = "{{#" + helperName + "}}should not appear{{/" + helperName + "}}";

            var template = handlebars.Compile(source);

            var output = template(null);

            var expected = string.Format(format, helperName.Trim('[', ']'));

            Assert.Equal(expected, output);
        }
示例#27
0
        public void MissingHelperHookViaHelperRegistration(string helperName)
        {
            var handlebars = Handlebars.Create();
            var format     = "Missing helper: {0}";

            handlebars.RegisterHelper("helperMissing", (context, arguments) =>
            {
                var name = arguments.Last().ToString();
                return(string.Format(format, name.Trim('[', ']')));
            });

            var source = "{{" + helperName + "}}";

            var template = handlebars.Compile(source);

            var output = template(null);

            var expected = string.Format(format, helperName.Trim('[', ']'));

            Assert.Equal(expected, output);
        }
        public void Generate_CSharp_from_output_model()
        {
            var ns      = new Namespace("MyApp.MyTest", null);
            var builder = new ClassOutputModelBuilder("test", null, new TestClassNamingConvention());

            builder.CreateClass("MyClass", ns);
            builder.CreateProperty("Name", "string");

            var outputModel = builder.Build();
            var instance    = Handlebars.Create(new HandlebarsConfiguration
            {
                TextEncoder = new NoopTextEncoder()
            });
            var template = new Template("test", instance, TemplateSource.CreateForText(@"
namespace {{Model.ClassNamespace}}
public class {{Model.ClassName}}
{
{{#each Model.Properties}}
    public {{Type.TypeName}} {{Name}} { get; set; }
{{/each}}
}
"));
            var renderer = new ClassOutputModelRenderer(template);
            var actual   = default(string);
            var expected = @"
namespace MyApp.MyTest
public class MyClass
{
    public string Name { get; set; }
}
";

            using (var writer = new StringWriter())
            {
                renderer.Render(outputModel, writer);
                actual = writer.ToString();
            }

            actual.Should().Be(expected);
        }
示例#29
0
        public void NestedObjectIteration()
        {
            const string template = @"
                {{#with test}}

					{{#if complexItems}}
					<ul>
						{{#each complexItems}}
							<li>{{name}} {{value}} {{evenMoreComplex.name}} {{evenMoreComplex.abbr}}</li>
						{{/each}}
					</ul>
					{{/if}}

				{{/with}}"                ;

            var data = new
            {
                test = new
                {
                    complexItems = new[] {
                        new { name = "a", value = 1, evenMoreComplex = new { name = "zzz", abbr = "z" } },
                        new { name = "b", value = 2, evenMoreComplex = new { name = "yyy", abbr = "y" } },
                        new { name = "c", value = 3, evenMoreComplex = new { name = "xxx", abbr = "x" } }
                    },
                }
            };

            var handlebars         = Handlebars.Create();
            var handlebarsTemplate = handlebars.Compile(template);

            var result = handlebarsTemplate(data);

            const string expected = "<ul><li>a 1 zzz z</li><li>b 2 yyy y</li><li>c 3 xxx x</li></ul>";
            var          actual   = result
                                    .Replace("\n", string.Empty)
                                    .Replace("\r", string.Empty)
                                    .Replace("\t", string.Empty);

            Assert.Equal(expected, actual);
        }
示例#30
0
        public void RegisterHelper()
        {
            var source = @"Click here: {{link_to}}";

            var handlebars = Handlebars.Create();

            handlebars.RegisterHelper("link_to", (writer, context, parameters) =>
            {
                writer.WriteSafeString($"<a href='{context["url"]}'>{context["text"]}</a>");
            });

            var template = handlebars.Compile(source);

            var data = new {
                url  = "https://github.com/rexm/handlebars.net",
                text = "Handlebars.Net"
            };

            var result = template(data);

            Assert.Equal($"Click here: <a href='{data.url}'>{data.text}</a>", result);
        }