示例#1
0
 public void RegisterHelperSample()
 {
     var helperjs =
         @"function() {
     return new Handlebars.SafeString(""<a href='"" + this.url + ""'>"" + this.body + ""</a>"");
     }";
     var source = @"
     <ul>
     {{#posts}}
     <li>{{link_to}}</li>
     {{/posts}}
     </ul>";
     var context = new
     {
         posts = new[]
         {
             new
             {
                 url = "/hello-world",
                 body = "Hello World!"
             }
         }
     };
     using (var handleBars = new Handlebars())
     {
         handleBars.RegisterHelper("link_to", helperjs);
         handleBars.RegisterTemplate("myTemplate", source);
         Approvals.Verify(handleBars.Transform("myTemplate", context));
     }
 }
示例#2
0
 public void CaseInsensitive()
 {
     var source = "Foo";
     using (var handleBars = new Handlebars())
     {
         handleBars.RegisterTemplate("mytemplate", source);
         Approvals.Verify(handleBars.Transform("myTemplate", null));
     }
 }
示例#3
0
    public void NewLineInTemplate()
    {
        var source = "AA\r\nBB";

        using (var handleBars = new Handlebars())
        {
            handleBars.RegisterTemplate("Index", source);
            Approvals.Verify(handleBars.Transform("Index", null));
        }
    }
示例#4
0
    public void MissingPartial()
    {
        var partial = @"<a href=""/people/{{id}}"">{{name}}</a>";

        var source = "{{> partial}}";

        using (var handleBars = new Handlebars())
        {
          //  handleBars.RegisterPartial("link", partial);
            handleBars.RegisterTemplate("myTemplate", source);
            Approvals.Verify(handleBars.Transform("myTemplate", null));
        }
    }
        public void DynamicPartial()
        {
            string source = "Hello, {{> (partialNameHelper)}}!";

            Handlebars.RegisterHelper("partialNameHelper", (writer, context, args) =>
            {
                writer.WriteSafeString("partialName");
            });

            using (var reader = new StringReader("world"))
            {
                var partial = Handlebars.Compile(reader);
                Handlebars.RegisterTemplate("partialName", partial);
            }

            var template = Handlebars.Compile(source);
            var data     = new { };
            var result   = template(data);

            Assert.Equal("Hello, world!", result);
        }
示例#6
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);
        }
示例#7
0
        public void BlockHelperWithSubExpression()
        {
            Handlebars.RegisterHelper("isEqual", (writer, context, args) =>
            {
                writer.WriteSafeString(args[0].ToString() == args[1].ToString() ? "true" : null);
            });

            var source = "{{#isEqual arg1 arg2}}{{/isEqual}} {{#if (isEqual arg1 arg2)}}True{{/if}}";

            var template = Handlebars.Compile(source);

            var expectedIsTrue = "True";
            var outputIsTrue   = template(new { arg1 = 1, arg2 = 1 });

            Assert.Equal(expectedIsTrue, outputIsTrue);

            var expectedIsFalse = "";
            var outputIsFalse   = template(new { arg1 = 1, arg2 = 2 });

            Assert.Equal(expectedIsFalse, outputIsFalse);
        }
        public void BasicInlinePartialWithContextAndStringParameters()
        {
            string source = "{{#*inline \"person\"}}{{first.name}} {{last}}{{/inline}}Hello, {{>person first=leadDev.marc last='Smith'}}!";

            var template = Handlebars.Compile(source);

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

            var result = template(data);

            Assert.Equal("Hello, Marc Smith!", result);
        }
示例#9
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);
        }
示例#10
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);
        }
示例#11
0
        public void HtmlIsNotEscapedInsideRawHelperHashArgs()
        {
            var inst   = Handlebars.Create();
            var source = "{{{{rawBlockHelper html foo=html}}}} {{ foo }} {{{{/rawBlockHelper}}}}";

            inst.RegisterHelper("rawBlockHelper", (writer, options, context, arguments) => {
                writer.Write(arguments[0]);
                options.Template(writer, null);
                writer.Write((arguments[1] as IDictionary <string, object>)["foo"]);
            });

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

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

            Assert.Equal("<div>foo</div> {{foo}} <div>foo</div>", output);
        }
示例#12
0
        public async Task Output(BuildContext context)
        {
            _logger.LogInformation($"------ Output Build:{context.BuildKey} Start! ------");
            var outputPath = Handlebars.Compile(context.Output.Path)(context);

            outputPath = Path.Combine(context.Project.OutputPath, outputPath);
            if (!Directory.Exists(outputPath))
            {
                Directory.CreateDirectory(outputPath);
                _logger.LogWarning($"------ Output Directory:{outputPath} is not Exists,Created! ------");
            }
            var fileName = Handlebars.Compile(context.Output.Name)(context) + context.Output.Extension;

            var filePath = Path.Combine(outputPath, fileName);

            using (StreamWriter streamWriter = new StreamWriter(filePath))
            {
                await streamWriter.WriteAsync(context.Result);
            }
            _logger.LogInformation($"------ Output Build:{context.BuildKey} -> {filePath} End! ------");
        }
示例#13
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);
        }
示例#14
0
        public void WHEN_Value_Contains_2_Options_SHOULD_replace_with_argument(string localizedValue, object arg0, object arg1, string expectedResult)
        {
            var localizationProvider = new Mock <ILocalizationProvider>(MockBehavior.Strict);

            localizationProvider
            .Setup(lp => lp.GetLocalizedString(It.IsNotNull <GetLocalizedParam>()))
            .Returns(localizedValue)
            .Verifiable();

            //Arrange
            var helpers = new LocalizeFormatHelper(localizationProvider.Object);

            Handlebars.RegisterHelper(helpers.HelperName, helpers.HelperFunction);
            var template = Handlebars.Compile("{{localizeFormat 'UseMock' 'UseMock' Arg0 Arg1}}");

            //Act
            var result = template.Invoke(new { Arg0 = arg0, Arg1 = arg1 });

            //Assert
            result.Should().BeEquivalentTo(expectedResult);
        }
        public void given_empty_path_context_where_context_is_generic_type()
        {
            var source        = "{{{dynPartial 'parPartialName' foo}}}";
            var partialSource = "test {{this.[0].bar}}";
            var template      = Handlebars.Compile(source);

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

            var data = new { foo = new List <vmBlock_PartialName>()
                             {
                                 new vmBlock_PartialName()
                             } };

            var output = template(data);

            Assert.AreEqual("test bar", output);
        }
示例#16
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);
        }
示例#17
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);
        }
        public void given_path_and_context_where_context_is_base_type(object input)
        {
            var source        = "{{{dynPartial 'partialName' foo}}}";
            var partialSource = "test {{this}}";
            var template      = Handlebars.Compile(source);

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

            var data = new
            {
                foo = input
            };

            var output = template(data);

            Assert.AreEqual($"test {input}", output);
        }
        public void Hbar()
        {
            string source =
                @"<div class=""entry"">
  <h1>{{title}}</h1>
  <div class=""body"">
    {{body}}
  </div>
</div>";
            var template = Handlebars.Compile(source);

            var data = new
            {
                title = "My new post",
                body  = "This is my first post!"
            };

            var result = template(data);

            Console.WriteLine(result);
        }
示例#20
0
        public string GenerateHtml(string ReportType, IEnumerable <KeyValuePair <string, StringValues> > Data = null)
        {
            var html = this.htmlDocumentService.GetDocument(ReportType);

            if (html == null)
            {
                throw new ArgumentException($"Could not find a report called {ReportType}");
            }
            var template = Handlebars.Compile(html);

            try
            {
                var data     = BuildReportData(ReportType, Data);
                var response = template(data);
                return(response);
            }
            catch (Exception ex)
            {
                throw new ArgumentException($"Could not Run Report, {ex.Message}", ex);
            }
        }
示例#21
0
        public async Task <bool> SendEmail <T>(string templateName, EmailAddress to, string subject, T context)
        {
            try
            {
                string htmlTemplate = _templateProvider.ReadFile(templateName);
                Handlebars.RegisterHelper("Message", RawOutput);
                var template = Handlebars.Compile(htmlTemplate);
                var msg      = MailHelper.CreateSingleEmail(From, to, subject, null, template(context));
#if DEBUG
                msg.SetClickTracking(false, false);
#endif
                var response = await _client.SendEmailAsync(msg);

                return(response.StatusCode == System.Net.HttpStatusCode.Accepted);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"An unexpected error occurred while processing an email:\nTemplate: {templateName}\nTo: {to.Email}\nSubject: {subject}");
                return(false);
            }
        }
示例#22
0
        public void BasicHelper()
        {
            Handlebars.RegisterHelper("link_to", (writer, context, parameters) =>
            {
                writer.WriteSafeString("<a href='" + parameters[0] + "'>" + parameters[1] + "</a>");
            });

            string source = @"Click here: {{link_to url text}}";

            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='https://github.com/rexm/handlebars.net'>Handlebars.Net</a>", result);
        }
示例#23
0
        public void HelperWithLiteralValues()
        {
            var source = "{{literalHelper true 1 \"abc\"}}";

            Handlebars.RegisterHelper("literalHelper", (writer, context, arguments) => {
                Assert.IsType <bool>(arguments[0]);
                Assert.IsType <int>(arguments[1]);
                Assert.IsType <string>(arguments[2]);
                writer.Write($"{arguments[0]} {arguments[1]} {arguments[2]}");
            });

            var data = new
            {
            };

            var template = Handlebars.Compile(source);

            var output = template(data);

            Assert.Equal("True 1 abc", output);
        }
示例#24
0
        MemoryStream AResult.Content()
        {
            string pathNew         = path.Replace("/bin/Debug", "");
            string defaultViewPath = pathNew + "/Views/" + this.controllerName;
            string customViewPath  = pathNew + "/Views/" + this.CustomView;

            byte[] dataDynamicView = null;

            customViewPath  += ".html";
            defaultViewPath += ".html";

            /// If the custom view parameter was entered.
            if (!string.IsNullOrEmpty(customViewPath))
            {
                if (File.Exists(customViewPath))
                {
                    dataDynamicView = File.ReadAllBytes(customViewPath);
                }
                else
                {
                    return(null);
                }
            }
            else  /// If the custom view parameter was not entered.
            {
                if (File.Exists(defaultViewPath))
                {
                    dataDynamicView = File.ReadAllBytes(defaultViewPath);
                }
                else
                {
                    return(null);
                }
            }

            var template = Handlebars.Compile(Encoding.Default.GetString(dataDynamicView));
            var result   = template(this.data);

            return(new MemoryStream(Encoding.ASCII.GetBytes(result)));
        }
示例#25
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);
        }
        public void BasicPartial()
        {
            string source = "Hello, {{>person}}!";

            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.AreEqual("Hello, Marc!", result);
        }
示例#27
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);
        }
示例#28
0
        public Templates(IPolicyConfiguration configuration)
        {
            m_logger = LoggerUtil.GetAppWideLogger();

            m_policyConfiguration = configuration;

            // Get our blocked HTML page
            byte[] htmlBytes = ResourceStreams.Get("FilterProvider.Common.Resources.BlockedPage.html");
            m_blockedHtmlPage = Handlebars.Compile(Encoding.UTF8.GetString(htmlBytes));

            m_badSslHtmlPage = ResourceStreams.Get("FilterProvider.Common.Resources.BadCertPage.html");

            if (m_blockedHtmlPage == null)
            {
                m_logger.Error("Could not load packed HTML block page.");
            }

            if (m_badSslHtmlPage == null)
            {
                m_logger.Error("Could not load packed HTML bad SSL page.");
            }
        }
示例#29
0
        public void DynamicPartialWithHelperArguments()
        {
            string source = "Hello, {{> (concat 'par' 'tial' item1='Na' item2='me')}}!";

            Handlebars.RegisterHelper("concat", (writer, context, args) =>
            {
                var hash = args[2] as Dictionary <string, object>;
                writer.WriteSafeString(string.Concat(args[0], args[1], hash["item1"], hash["item2"]));
            });

            using (var reader = new StringReader("world"))
            {
                var partial = Handlebars.Compile(reader);
                Handlebars.RegisterTemplate("partialName", partial);
            }

            var template = Handlebars.Compile(source);
            var data     = new { };
            var result   = template(data);

            Assert.Equal("Hello, world!", result);
        }
示例#30
0
        public void CanUseDictionaryModelInLayout()
        {
            var files = new FakeFileSystem
            {
                { "views\\layout.hbs", "Layout: {{property}}\r\n{{{body}}}" },
                { "views\\someview.hbs", "{{!< layout}}\r\n\r\nBody: {{property}}" },
            };

            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>
            {
                { "property", "Foo" },
            }
                );

            Assert.Equal("Layout: Foo\r\n\r\nBody: Foo", output);
        }
示例#31
0
        public void BasicSubExpressionWithStringLiteralArgument()
        {
            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 'inner-arg')}}";

            var template = handlebars.Compile(source);

            var output = template(new { });

            var expected = "Outer Inner inner-arg";

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

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

            handlebars.RegisterHelper("add", (writer, context, args) => {
                writer.Write((int)args[0] + (int)args[1]);
            });

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

            var template = handlebars.Compile(source);

            var output = template(new { });

            var expected = "3 hello";

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

            handlebars.RegisterHelper("math", (writer, context, args) => {
                writer.Write("Math " + args[0] + " " + args[1]);
            });

            handlebars.RegisterHelper("add", (writer, context, args) => {
                writer.Write((int)args[0] + (int)args[1]);
            });

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

            var template = handlebars.Compile(source);

            var output = template(new { });

            var expected = "Math 3 7";

            Assert.Equal(expected, output);
        }
示例#34
0
        public TemplateEngine(TemplateEngineServices services, TemplateEngineOptions options)
        {
            Services = services;
            Options  = options;
            var config = new HandlebarsConfiguration()
            {
                FileSystem = new ProbingFileSystem(options.FileSystem),
                Helpers    =
                {
                    { "query",    QueryHelper    },
                    { "json",     JsonHelper     },
                    { "yaml",     YamlHelper     },
                    { "guid",     GuidHelper     },
                    { "datetime", DateTimeHelper },
                    { "secret",   SecretHelper   },
                },
                BlockHelpers =
                {
                    { "query",  QueryBlockHelper  },
                    { "indent", IndentBlockHelper },
                },
                TextEncoder = new SimpleEncoder(),
            };

            foreach (var templateHelperProvider in services.TemplateHelperProviders)
            {
                foreach (var helper in templateHelperProvider.GetHelpers())
                {
                    config.Helpers[helper.Key] = helper.Value;
                }

                foreach (var helper in templateHelperProvider.GetBlockHelpers())
                {
                    config.BlockHelpers[helper.Key] = helper.Value;
                }
            }

            _compiler = Handlebars.Create(config);
        }
示例#35
0
    public void Sample()
    {
        var source = @"
        <p>Hello, my name is {{name}}. I am from {{hometown}}. I have {{kids.length}} kids:</p>
        <ul>
        {{#kids}}
        <li>{{name}} is {{age}}</li>
        {{/kids}}
        </ul>";

        var context = new
        {
            name = "Alan",
            hometown = "Somewhere, TX",
            kids = new[]
            {
                new
                {
                    name = "Sally",
                    age = "4"
                }
            }
        };

        using (var handleBars = new Handlebars())
        {
            handleBars.RegisterTemplate("Index", source);
            Approvals.Verify(handleBars.Transform("Index", context));
        }
    }
示例#36
0
    public void RegisterPartialsSample()
    {
        var partial = @"<a href=""/people/{{id}}"">{{name}}</a>";

        var source = @"
        <ul>
        {{#people}}
        <li>{{> link}}</li>
        {{/people}}
        </ul>";

        var context = new
        {
            people = new[]
            {
                new
                {
                    name = "Alan",
                    id = 1
                },
                new
                {
                    name = "Yehuda",
                    id = 2
                }
            }
        };
        using (var handleBars = new Handlebars())
        {
            handleBars.RegisterPartial("link", partial);
            handleBars.RegisterTemplate("myTemplate", source);
            Approvals.Verify(handleBars.Transform("myTemplate", context));
        }
    }
示例#37
0
    /***********************************************************
     * Methode: Start
     * Beschreibung: Initialisierung der Skriptreferenzen und
     * Checkboxstatus
     * Parameter: keine
     * Rückgabewert: keiner
     ***********************************************************/
    void Start()
    {
        startPos = Bike.transform.position;
        startRot = Bike.transform.eulerAngles;
        moveBike = Bike.GetComponent<MoveBike>();
        moveBikeAuto = Bike.GetComponent<AutoMove>();

        bikePitch = BikeBody.GetComponent<BikePitch>();

        handlebars = Handlebars.GetComponent<Handlebars>();
        autoSteer = Handlebars.GetComponent<AutoSteer>();

        toggleMove.isOn = moveBike.enabled;
        togglePitch.isOn = bikePitch.enabled;
        toggleHandle.isOn = handlebars.enabled;
    }