public void DictionaryIteration() { string source = @"{{#ADictionary}}{{@key}},{{value}}{{/ADictionary}}"; var template = Handlebars.Compile(source); var result = template(new { ADictionary = new Dictionary <string, int> { { "key5", 14 }, { "key6", 15 }, { "key7", 16 }, { "key8", 17 } } }); Assert.AreEqual("key5,14key6,15key7,16key8,17", result); }
public void WHEN_Value_Contains_10_Options_SHOULD_replace_with_argument( string localizedValue, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, 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 Arg2 Arg3 Arg4 Arg5 Arg6 Arg7 Arg8 Arg9}}"); //Act var result = template.Invoke(new { Arg0 = arg0, Arg1 = arg1, Arg2 = arg2, Arg3 = arg3, Arg4 = arg4, Arg5 = arg5, Arg6 = arg6, Arg7 = arg7, Arg8 = arg8, Arg9 = arg9 }); //Assert result.Should().BeEquivalentTo(expectedResult); }
public async Task Output(BuildContext context, Output output = null) { if (output == null) { output = context.Output; } _logger.LogInformation($"------ Mode:{output.Mode},Build:{context.BuildKey} Start! ------"); var outputPath = Handlebars.Compile(output.Path)(context); outputPath = Path.Combine(context.Project.OutputPath, outputPath); if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); _logger.LogWarning($"------ Directory:{outputPath} is not Exists,Created! ------"); } var fileName = Handlebars.Compile(output.Name)(context) + output.Extension; var filePath = Path.Combine(outputPath, fileName); var fileExists = File.Exists(filePath); if (fileExists) { switch (output.Mode) { case Configuration.CreateMode.None: case Configuration.CreateMode.Incre: { _logger.LogWarning($"------ Mode:{output.Mode},Build:{context.BuildKey},FilePath:{filePath} Exists ignore output End! ------"); return; } case Configuration.CreateMode.Full: { File.Delete(filePath); _logger.LogWarning($"------ Mode:{output.Mode},FilePath:{filePath} Exists Deleted ! ------"); break; } } } using (StreamWriter streamWriter = new StreamWriter(filePath)) { await streamWriter.WriteAsync(context.Result); } _logger.LogInformation($"------ Mode:{output.Mode},Build:{context.BuildKey} -> {filePath} End! ------"); }
public void given_empty_path_context_and_parameter() { var source = "{{{modPartial '' foo '' param='test'}}}"; var partialSource = "test {{bar}} {{param}}"; 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 vmBlock_PartialName() }; var output = template(data); Assert.AreEqual("test bar test", output); }
public void given_empty_path_and_context_is_array() { var source = "{{{modPartial '' foo ''}}}"; var partialSource = "test {{#each this}}{{this.bar}}{{/each}}"; 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[] { new vmBlock_PartialName() } }; var output = template(data); Assert.AreEqual("test bar", output); }
public static string GetHtml <T>(T data, string templateName) { var basePath = System.Web.Hosting.HostingEnvironment.MapPath(TemplateFolder); var totalPath = Path.Combine(basePath, templateName); if (!File.Exists(totalPath)) { throw new InvalidOperationException("La plantilla {0} no se ha encontrado en el folder de plantillas."); } var templateText = File.ReadAllText(totalPath); var template = Handlebars.Compile(templateText); var result = template(data); return(result); }
public void EmptyBlockHelperWithInversion() { var source = "{{#ifCond}}{{else}}Inverse{{/ifCond}}"; Handlebars.RegisterHelper("ifCond", (writer, options, context, arguments) => { options.Inverse(writer, (object)context); }); var data = new { }; var template = Handlebars.Compile(source); var output = template(data); Assert.Equal("Inverse", output); }
public void BlockPartialWithSpecialNamedPartial() { string source = "Well, {{#>myPartial}}some test{{/myPartial}} !"; var template = Handlebars.Compile(source); var partialSource = "this is {{> @partial-block }} content"; using (var reader = new StringReader(partialSource)) { var partialTemplate = Handlebars.Compile(reader); Handlebars.RegisterTemplate("myPartial", partialTemplate); } var data = new { }; var result = template(data); Assert.Equal("Well, this is some test content !", result); }
public void BasicPartialWithStringParameter() { string source = "Hello, {{>person first='Pete'}}!"; var template = Handlebars.Compile(source); var partialSource = "{{first}}"; using (var reader = new StringReader(partialSource)) { var partialTemplate = Handlebars.Compile(reader); Handlebars.RegisterTemplate("person", partialTemplate); } var result = template(null); Assert.Equal("Hello, Pete!", result); }
public static string Result() { Handlebars.RegisterHelper("link_to", (writer, context, parameters) => { writer.WriteSafeString("<a href='" + "URL" + "'>" + "TEXT" + "</a>"); }); var template = Handlebars.Compile(source); var data = new { url = "https://github.com/rexm/handlebars.net", text = "Handlebars.Net" }; var result = template(data); return(result); }
public void MissingHelperHookWhenVariableExists() { var handlebars = Handlebars.Create(); var expected = "Variable"; handlebars.Configuration .RegisterMissingHelperHook( (context, arguments) => "Hook" ); var source = "{{missing}}"; var template = Handlebars.Compile(source); var output = template(new { missing = "Variable" }); Assert.Equal(expected, output); }
static void Main(string[] args) { // Compile the template var stringTemplate = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + @"..\..\HubTemplate.handlebars"); var template = Handlebars.Compile(stringTemplate); // Retrieve metadata and store in a data table object var jsonInput = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + @"..\..\sample.json"); DataObjectMappingList deserialisedMapping = JsonConvert.DeserializeObject <DataObjectMappingList>(jsonInput); // Return the result to the user var result = template(deserialisedMapping); Console.WriteLine(result); Console.ReadKey(); }
public void BasicDeferredBlockEnumerable() { string source = "Hello, {{#people}}{{this}} {{/people}}!"; var template = Handlebars.Compile(source); var data = new { people = new[] { "Bill", "Mary" } }; var result = template(data); Assert.Equal("Hello, Bill Mary !", result); }
public void BasicIterator() { var source = "Hello,{{#each people}}\n- {{name}}{{/each}}"; var template = Handlebars.Compile(source); var data = new { people = new [] { new { name = "Erik" }, new { name = "Helen" } } }; var result = template(data); Assert.AreEqual("Hello,\n- Erik\n- Helen", result); }
public void BasicIfElseIf() { var source = "{{#if isActive}}active{{else if isInactive}}inactive{{/if}}"; var template = Handlebars.Compile(source); var activeData = new { isActive = true }; var inactiveData = new { isInactive = true }; var resultTrue = template(activeData); var resultFalse = template(inactiveData); Assert.Equal("active", resultTrue); Assert.Equal("inactive", resultFalse); }
public void BasicDeferredBlockWithWhitespace() { string source = "Hello, {{ # person }}{{ name }}{{ / person }}!"; var template = Handlebars.Compile(source); var data = new { person = new { name = "Bill" } }; var result = template(data); Assert.Equal("Hello, Bill!", result); }
public void BasicIfElse() { var source = "Hello, {{#if basic_bool}}Bob{{else}}Sam{{/if}}!"; var template = Handlebars.Compile(source); var trueData = new { basic_bool = true }; var falseData = new { basic_bool = false }; var resultTrue = template(trueData); var resultFalse = template(falseData); Assert.Equal("Hello, Bob!", resultTrue); Assert.Equal("Hello, Sam!", resultFalse); }
public CommandBase(ILogger <object> logger) { this.CurrentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); this.AssemblyVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); this.Logger = logger; var data = new { toolName = Constants.CLIName, version = this.AssemblyVersion }; var templateSource = File.ReadAllText(Path.Combine(this.CurrentPath, Constants.TemplatesFolderName, "Sign.Template")); var template = Handlebars.Compile(templateSource); this.Sign = template(data); Handlebars.RegisterTemplate("sign", templateSource); }
public async Task Handle(HttpRequest req, HttpResponse res, object model, CancellationToken cancellationToken) { var source = viewLocator.GetView(model, res.HttpContext); if (string.IsNullOrEmpty(source)) { res.StatusCode = 500; res.ContentType = "text/plain"; await res.WriteAsync("View not found", cancellationToken); } var template = Handlebars.Compile(source); res.ContentType = "text/html"; res.StatusCode = (int)HttpStatusCode.OK; await res.WriteAsync(template(model), cancellationToken); }
public void BasicInlinePartialWithContext() { string source = "{{#*inline \"person\"}}{{name}}{{/inline}}Hello, {{>person leadDev}}!"; var template = Handlebars.Compile(source); var data = new { leadDev = new { name = "Marc" } }; var result = template(data); Assert.Equal("Hello, Marc!", result); }
public void BasicStringOnlyPartial() { string source = "Hello, {{>person}}!"; var template = Handlebars.Compile(source); var data = new { name = "Marc" }; var partialSource = "{{name}}"; Handlebars.RegisterTemplate("person", partialSource); var result = template(data); Assert.Equal("Hello, Marc!", result); }
/// <summary> /// Set Application Template Main /// </summary> /// <param name="application"></param> /// <param name="handlebarsTemplate"></param> /// <returns></returns> public static string PopulateHtmlTemplateWithApplicationData(ApplicationSubmission application, string handlebarsTemplate) { Handlebars.RegisterHelper("boolOrString", (writer, context, parameters) => { string value = parameters[0].ToString(); switch (value.ToLower()) { case "true": value = "Yes"; break; case "false": value = "No"; break; case "": value = "NOT PROVIDED"; break; } writer.WriteSafeString(value); }); Handlebars.RegisterHelper("formatAddress", (writer, context, parameters) => { if (parameters[0].GetType() == typeof(Address)) { Address value = (Address)parameters[0]; writer.WriteSafeString($"{value.StreetAddress}<div>{value.City}, {value.State} {value.ZipCode}</div><div>{value.County}</div>"); } }); Handlebars.RegisterHelper("formatAttachment", (writer, context, parameters) => { if (parameters[0].GetType() == typeof(Attachment)) { Attachment value = (Attachment)parameters[0]; writer.WriteSafeString($"<div>{value.OriginalFileName}</div>"); } }); var template = Handlebars.Compile(handlebarsTemplate); return(template(application)); }
private static void RunAutomation(Options options, string inputFileName, string outputFileName = "") { try { var jsonInput = File.ReadAllText(inputFileName); var stringTemplate = File.ReadAllText(options.pattern); var template = Handlebars.Compile(stringTemplate); // var deserialisedMapping = JsonConvert.DeserializeObject<VdwDataObjectMappings>(jsonInput); var freeFormMapping = JObject.Parse(jsonInput); var result = template(freeFormMapping); if (options.verbose) { Console.WriteLine(result); } if (options.output) { if (outputFileName == "") { //outputFileName = deserialisedMapping.dataObjectMappings[0].mappingName; // you could read this from the free form mapping file, too outputFileName = (string)freeFormMapping["mappingName"]; // you could read this from the free form mapping file, too } Console.WriteLine($"Generating {outputFileName}.{options.outputFileExtension} to {options.outputDirectory}."); using (StreamWriter file = new StreamWriter($"{options.outputDirectory}\\{outputFileName}.{options.outputFileExtension}")) { file.WriteLine(result); } } Environment.ExitCode = (int)ExitCode.Success; } catch (Exception ex) { if (options.verbose) { Console.WriteLine($"An error has been encountered: {ex}"); } Environment.ExitCode = (int)ExitCode.UnknownError; } }
public void DeepIf() { var source = @"{{#if outer_bool}} {{#with a}}{{#if inner_bool}}a is true{{else}}a is false{{/if}}{{/with}} {{else}} {{#with b}}{{#if inner_bool}}b is true{{else}}b is false{{/if}}{{/with}} {{/if}}"; var template = Handlebars.Compile(source); var trueTrue = new { outer_bool = true, a = new { inner_bool = true } }; var trueFalse = new { outer_bool = true, a = new { inner_bool = false } }; var falseTrue = new { outer_bool = false, b = new { inner_bool = true } }; var falseFalse = new { outer_bool = false, b = new { inner_bool = false } }; var resultTrueTrue = template(trueTrue); var resultTrueFalse = template(trueFalse); var resultFalseTrue = template(falseTrue); var resultFalseFalse = template(falseFalse); Assert.AreEqual("\na is true\n", resultTrueTrue); Assert.AreEqual("\na is false\n", resultTrueFalse); Assert.AreEqual("\nb is true\n", resultFalseTrue); Assert.AreEqual("\nb is false\n", resultFalseFalse); }
public void BasicIteratorWithFirst() { var source = "Hello,{{#each people}}\n{{@index}}. {{name}} ({{#with @first}}{{name}} is first{{/with}}){{/each}}"; var template = Handlebars.Compile(source); var data = new { people = new[] { new { name = "Erik" }, new { name = "Helen" } } }; var result = template(data); Assert.AreEqual("Hello,\n0. Erik (Erik is first)\n1. Helen (Erik is first)", result); }
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.AreEqual("Click here: <a href='https://github.com/rexm/handlebars.net'>Handlebars.Net</a>", result); }
public void WithIndex() { var source = "Hello,{{#each people}}\n{{@index}}. {{name}}{{/each}}"; var template = Handlebars.Compile(source); var data = new { people = new[] { new { name = "Erik" }, new { name = "Helen" } } }; var result = template(data); Assert.Equal("Hello,\n0. Erik\n1. Helen", result); }
public void EmptyElementTemplate() { var source = "Hello,{{#each people}}{{/each}}"; var template = Handlebars.Compile(source); var data = new { people = new[] { new { name = "Erik" }, new { name = "Helen" } } }; var result = template(data); Assert.Equal("Hello,", result); }
public void WithLast() { var source = "Hello,{{#each people}}\n{{@index}}. {{name}} ({{name}} is {{#if @last}}last{{else}}not last{{/if}}){{/each}}"; var template = Handlebars.Compile(source); var data = new { people = new[] { new { name = "Erik" }, new { name = "Helen" } } }; var result = template(data); Assert.Equal("Hello,\n0. Erik (Erik is not last)\n1. Helen (Helen is last)", result); }
public void StandalonePartials() { string source = "Here are:\n {{>person}} \n {{>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.Equal("Here are:\nMarcMarc", result); }