public void Auto_Cascase_Partial_Loaders_On_Add() { var stubble = new StubbleBuilder() .AddToPartialTemplateLoader(new DictionaryLoader(new Dictionary<string, string> { {"Foo", "I'm Foo"}, {"Bar", "I'm Bar"} })).Build(); Assert.Equal("I'm Foo", stubble.Render("{{> Foo}}", new { foo = "blah" })); Assert.Equal("bar", stubble.Render("{{foo}}", new { foo = "bar" })); }
public void It_Can_Render_WithPartials_FromLoader() { var stubble = new StubbleBuilder() .SetPartialTemplateLoader(new DictionaryLoader(new Dictionary<string, string> { {"foo", "{{Foo}} this"} })).Build(); var output = stubble.Render("{{> foo}}", new { Foo = "Bar" }); Assert.Equal("Bar this", output); }
public void It_Can_Render_WithPartials_FromLoader() { var stubble = new StubbleBuilder() .Configure(b => b.SetPartialTemplateLoader(new DictionaryLoader(new Dictionary <string, string> { { "foo", "{{Foo}} this" } }))) .Build(); var output = stubble.Render("{{> foo}}", new { Foo = "Bar" }); Assert.Equal("Bar this", output); }
public void Execute(Configuration configuration, List <Duplicate> duplicates) { var stubble = new StubbleBuilder().Build(); var data = new Dictionary <string, object> { ["Duplicates"] = duplicates.Select(q => new DuplicateDisplay(configuration.SourceDirectory, q)).ToList(), ["Configuration"] = configuration, }; var output = stubble.Render(Template, data); RenderFileHelper.SaveRenderOutput(configuration, FileName, output); }
public void It_Should_Not_Render_If_Partial_Doesnt_Exist_In_Loader() { var stubble = new StubbleBuilder() .Configure(b => b.SetPartialTemplateLoader(new DictionaryLoader(new Dictionary <string, string> { { "foo", "{{Foo}} this" } }))) .Build(); var output = stubble.Render("{{> foo2}}", new { Foo = "Bar" }); Assert.Equal("", output); }
public void It_Can_Get_Values_From_JTokens() { const string json = "{ foo: \"bar\" }"; var stubble = new StubbleBuilder() .Configure(settings => settings.AddJsonNet()) .Build(); var obj = JsonConvert.DeserializeObject(json); var output = stubble.Render("{{foo}}", obj); Assert.Equal("bar", output); }
protected override void Execute(CodeActivityContext context) { var templateString = TemplateString.Get(context); var templatePath = TemplatePath.Get(context); var obj = InputObject.Get(context); var stubble = new StubbleBuilder().Build(); string output; if (!string.IsNullOrEmpty(templateString)) { output = stubble.Render(templateString, obj); } else { using (StreamReader streamReader = new StreamReader(templatePath, Encoding.UTF8)) { output = stubble.Render(streamReader.ReadToEnd(), obj); } } Output.Set(context, output); }
public void It_Doesnt_Throw_When_No_Value_Exists() { const string json = "{ foo: \"bar\" }"; var stubble = new StubbleBuilder() .Configure(settings => settings.AddJsonNet()) .Build(); var obj = JsonConvert.DeserializeObject(json); var output = stubble.Render("{{foo2}}", obj); Assert.Equal("", output); }
public IEnumerable <TemplateFile> Render(IEnumerable <TemplateFile> files, Dictionary <string, object> tags, Dictionary <string, string> tagRegexes) { var conditionalTags = tags.Where(x => x.Value is bool)?.Select(x => x.Key); var filesWithFormat = files.Where(x => x.Content.Contains(LOWER_CASE) || x.Content.Contains(UPPER_CASE) || x.Name.Contains(LOWER_CASE) || x.Name.Contains(UPPER_CASE)); foreach (var tag in tags.Where(x => x.Value is string && filesWithFormat.Any(y => y.Content.Contains($"{x.Key}__") || y.Name.Contains($"{x.Key}__"))).ToArray()) { tags.Add($"{tag.Key}{LOWER_CASE}", tag.Value.ToString().ToLowerInvariant()); tags.Add($"{tag.Key}{UPPER_CASE}", tag.Value.ToString().ToUpperInvariant()); } try { var stubble = new StubbleBuilder().Build(); return(files.Select(x => { if (conditionalTags != null) { foreach (var tag in conditionalTags) { x.Name = x.Name.Replace("{{" + tag + "}}", string.Empty); } } return new TemplateFile { Name = stubble.Render(x.Name, tags), Content = stubble.Render(x.Content, tags) }; })); } catch (Exception ex) { throw new TemplateException(ex.Message, ex); } }
public void It_Handles_Arrays_Correctly() { const string json = "{ foo: [ { bar: \"foobar\" } ] }"; var stubble = new StubbleBuilder() .Configure(settings => settings.AddJsonNet()) .Build(); var obj = JsonConvert.DeserializeObject(json); var output = stubble.Render("{{#foo}}{{bar}}{{/foo}}", obj); Assert.NotNull(output); Assert.Equal("foobar", output); }
public void It_Handles_Nested_Objects() { const string json = "{ foo: { bar: \"foobar\" } }"; var stubble = new StubbleBuilder() .Configure(settings => settings.AddJsonNet()) .Build(); var obj = JsonConvert.DeserializeObject(json); var output = stubble.Render("{{foo.bar}}", obj); Assert.NotNull(output); Assert.Equal("foobar", output); }
public void It_Handles_Primative_Arrays_Correctly() { const string json = "{ foo: [ \"a\", \"b\", \"c\" ] }"; var stubble = new StubbleBuilder() .Configure(settings => settings.AddJsonNet()) .Build(); var obj = JsonConvert.DeserializeObject(json); var output = stubble.Render("{{#foo}}{{.}}{{/foo}}", obj); Assert.NotNull(output); Assert.Equal("abc", output); }
public static string Generate(string template, object model) { if (template == null) { throw new ArgumentNullException(nameof(template)); } if (model == null) { throw new ArgumentNullException(nameof(model)); } var stubble = new StubbleBuilder().Build(); return(stubble.Render(template, model)); }
public void It_Handles_Nested_Objects_With_Variables_Within_Sections() { const string json = "{ \"foo\": { \"bar\": \"foobar\" } }"; var stubble = new StubbleBuilder() .Configure(settings => settings.AddJsonNet()) .Build(); var obj = JsonConvert.DeserializeObject(json); var output = stubble.Render("{{#foo}}{{bar}}{{/foo}}", obj); Assert.NotNull(output); Assert.Equal("foobar", output); }
public void Truthy_Checks_Work_For_Inverted() { const string json = "{ showme: false, foo: { bar: \"foobar\" } }"; var stubble = new StubbleBuilder() .Configure(settings => settings.AddJsonNet()) .Build(); var obj = JsonConvert.DeserializeObject(json); var output = stubble.Render("{{^showme}}{{foo.bar}}{{/showme}}", obj); Assert.NotNull(output); Assert.Equal("foobar", output); }
public void Truthy_Checks_Work_Correctly() { const string json = "{ showme: false, foo: { bar: \"foobar\" } }"; var stubble = new StubbleBuilder() .AddJsonNet() .Build(); var obj = JsonConvert.DeserializeObject(json); var output = stubble.Render("{{#showme}}{{foo.bar}}{{/showme}}", obj); Assert.NotNull(output); Assert.Equal("", output); }
public void ItShouldRenderHelperWithTwoConstantArguments() { var helpers = new Helpers() .Register("ReplaceString", (HelperContext context, string searchString, string oldString, string newString) => searchString?.Replace(oldString, newString, StringComparison.InvariantCulture)); var renderer = new StubbleBuilder() .Configure(conf => conf.AddHelpers(helpers)) .Build(); var result = renderer.Render("Name: {{ReplaceString Name 'XXX' ' '}}", new { Name = "JohnXXXSmith" }); Assert.Equal("Name: John Smith", result); }
public void ItShouldRenderHelperWithConstantQuotedStringArgument() { var helpers = new Helpers() .Register <string>("ToCapitalLetters", (context, arg) => arg.ToUpperInvariant()); var renderer = new StubbleBuilder() .Configure(conf => conf.AddHelpers(helpers)) .Build(); var res = renderer.Render("User name is '{{Name}}' and nickname is '{{Nickname}}'. In capital letters name is '{{ToCapitalLetters Name}}' and nickname is '{{ToCapitalLetters 'Nickname'}}'", new { Name = "John" }); Assert.Equal("User name is 'John' and nickname is ''. In capital letters name is 'JOHN' and nickname is 'NICKNAME'", res); }
public void ItShouldNotRenderHelperWithMissingLookedUpArgumentThatIsntValueType() { var helpers = new Helpers() .Register <string>("ToCapitalLetters", (context, arg) => arg.ToUpperInvariant()); var renderer = new StubbleBuilder() .Configure(conf => conf.AddHelpers(helpers)) .Build(); var res = renderer.Render("User name is '{{Name}}' and nickname is '{{Nickname}}'. In capital letters name is '{{ToCapitalLetters Name}}' and nickname is '{{ToCapitalLetters Nickname}}'", new { Name = "John" }); Assert.Equal("User name is 'John' and nickname is ''. In capital letters name is 'JOHN' and nickname is ''", res); }
public void It_Can_Render_Dictionary_WithIgnoreCaseTrue() { var stubble = new StubbleBuilder() .Configure(b => { b.SetIgnoreCaseOnKeyLookup(true); }) .Build(); var output = stubble.Render("{{foo}}", new Dictionary <string, object>() { { "Foo", "Bar" } }); Assert.Equal("Bar", output); }
/// <summary> /// To generate Code File based on Mustache File and JSON file /// </summary> /// <param name="fileName"> Code File to be created</param> /// <param name="jsonObject">JSON Object which contains all values for parsing Mustache file</param> /// <returns></returns> public static async Task <string> GenerateCodeFile(string fileName, string codeFilePath, JObject jsonObject) { var stubble = new StubbleBuilder().Configure(settings => settings.AddJsonNet()).Build(); string startupMustacheFile = Directory.GetCurrentDirectory() + @"\Templates\AspDotNetCoreTemplate\" + fileName + ".Mustache"; string codeOutput = string.Empty; using (StreamReader streamReader = new StreamReader(startupMustacheFile, Encoding.UTF8)) { codeOutput = stubble.Render(streamReader.ReadToEnd(), jsonObject); await File.WriteAllTextAsync(codeFilePath, codeOutput); } return(codeOutput); }
public void It_Should_Skip_Html_Encoding_With_Setting() { var stubble = new StubbleBuilder() .Build(); var obj = new { Html = "<b>Html</b>" }; var result = stubble.Render("{{Html}}\n{{{Html}}}", obj, new RenderSettings { SkipHtmlEncoding = true }); Assert.Equal("<b>Html</b>\n<b>Html</b>", result); }
/// <summary> /// Creates the output document. /// </summary> private void CreateOutputDocument() { var currentDir = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location) ?? "."; var contentTemplate = File.ReadAllText(Path.Combine(currentDir, "Templates", "Content.html")); var reportTemplate = File.ReadAllText(Path.Combine(currentDir, "Templates", "Report.html")); // Render Content var stubble = new StubbleBuilder().Build(); var projectsContent = stubble.Render(contentTemplate, new { Projects = CodeProjects }); // Insert content into report file var report = reportTemplate.Replace("{{PROJECTS}}", projectsContent); var directory = new FileInfo(_options.ReportPath).Directory.FullName; Directory.CreateDirectory(directory); File.WriteAllText(_options.ReportPath, report); }
public override Stream GetStream() { var stubble = new StubbleBuilder() .Configure(settings => { settings.SetIgnoreCaseOnKeyLookup(true); settings.SetMaxRecursionDepth(512); }) .Build(); var encoded = Encoding.ASCII.GetBytes( stubble.Render(new StreamReader($"{ProjectPath}/Templates/errors.html", Encoding.UTF8).ReadToEnd(), new { Title = "Error", ErrorText = StatusCode.ToString() }) ); return(new MemoryStream(encoded)); }
public async Task <IActionResult> GetHash([FromBody] Dictionary <string, object> rawdata, string template) { // first do a mustache merge. var stubble = new StubbleBuilder().Build(); string filename = $"Templates/{template}.mustache"; if (System.IO.File.Exists(filename)) { string format = System.IO.File.ReadAllText(filename); var html = stubble.Render(format, rawdata); // compute a hash of the template to render as PDF var hash = HashUtility.GetSHA256(Encoding.UTF8.GetBytes(html)); return(new JsonResult(new { hash = hash })); } return(new NotFoundResult()); }
public IActionResult GetPDF([FromBody] Dictionary <string, object> rawdata, string template) { // first do a mustache merge. var stubble = new StubbleBuilder().Build(); string filename = $"Templates/{template}.mustache"; if (System.IO.File.Exists(filename)) { string format = System.IO.File.ReadAllText(filename); var html = stubble.Render(format, rawdata); var doc = new HtmlToPdfDocument() { GlobalSettings = { PaperSize = PaperKind.Letter, Orientation = Orientation.Portrait, Margins = new MarginSettings(5.0, 5.0, 5.0, 5.0) }, Objects = { new ObjectSettings() { HtmlContent = html } } }; try { var pdf = _generatePdf.Convert(doc); return(File(pdf, "application/pdf")); } catch (Exception e) { _logger.LogError(e, "ERROR rendering PDF"); _logger.LogError(template); _logger.LogError(html); } } return(new NotFoundResult()); }
void travisOverrideTemplates(CustomVersion version, string selectedNamespace = null) { if (selectedNamespace == null) { selectedNamespace = K8sNamespace ?? Branch; } var dataHash = new Dictionary <string, object>() { { "dockerVer", version.ToDockerTag() }, { "namespace", selectedNamespace }, }; var stubble = new StubbleBuilder().Build(); using (var streamReader = new StreamReader(TravisTemplateFile, Encoding.UTF8)) { var content = stubble.Render(streamReader.ReadToEnd(), dataHash); File.WriteAllText(TravisFile, content); } }
public void HelpersShouldBeAbleToHaveStaticParameterWithEscapedQuotes() { var helpers = new Helpers() .Register <string, string>("DefaultMe", (context, str, @default) => { return(string.IsNullOrEmpty(str) ? @default : str); }); var builder = new StubbleBuilder() .Configure(conf => { conf.AddHelpers(helpers); }) .Build(); var tmpl = @"{{DefaultMe Value 'I\'m Defaulted'}}"; var res = builder.Render(tmpl, new { Value = "" }); Assert.Equal("I'm Defaulted", res); }
public void It_Should_Allow_A_Render_Function_WithContext_In_Lambda() { var stubble = new StubbleBuilder() .Build(); var obj = new { Value = "a", ValueDictionary = new Dictionary <string, string> { { "a", "A is Cool" }, { "b", "B is Cool" }, }, ValueRender = new Func <dynamic, string, Func <string, string>, object>((dynamic ctx, string text, Func <string, string> render) => "{{ValueDictionary." + render(ctx.Value) + "}}") }; var result = stubble.Render("{{#ValueRender}}{{/ValueRender}}", obj); Assert.Equal("A is Cool", result); }
protected override void ProcessRecord() { var s = new RendererSettingsBuilder().BuildSettings(); if (SkipHtmlEncoding) { s.RenderSettings.SkipHtmlEncoding = true; } var stubble = new StubbleBuilder().Configure(settings => settings.AddJsonNet()).Build(); var data = JsonConvert.DeserializeObject(json); string output = stubble.Render(template, data, s.RenderSettings); if (useCustomWhiteSpaceClearner) { output = CustomWhiteSpaceCleaner(output); } WriteObject(output); }
public void HelpersShouldBeAbleToHaveStaticAndDynamicParameters() { var helpers = new Helpers() .Register <decimal, decimal>("Multiply", (context, count, multiplier) => { return($"{count * multiplier}"); }); var builder = new StubbleBuilder() .Configure(conf => { conf.AddHelpers(helpers); }) .Build(); var tmpl = @"{{Multiply 5 5}}, {{Multiply Count 5}}"; var res = builder.Render(tmpl, new { Count = 2 }); Assert.Equal("25, 10", res); }
public void ItShouldCallHelperWhenExistsStaticAndDynamicVariable(string staticValue) { var helpers = new Helpers() .Register <string, int>("MyHelper", (context, staticVariable, dynamicVariable) => { return($"<{staticVariable}#{dynamicVariable}>"); }); var builder = new StubbleBuilder() .Configure(conf => { conf.AddHelpers(helpers); }) .Build(); var tmpl = @"{{MyHelper " + staticValue + " Count }}"; var res = builder.Render(tmpl, new { Count = 10 }); Assert.Equal($"<Count#10>", res); }
public void It_Should_Have_Fresh_Depth_On_Each_Render() { var stubble = new StubbleBuilder().SetMaxRecursionDepth(128).Build(); for (var i = 0; i < 256; i++) { Assert.NotNull(stubble.Render("{{Foo}}", new { Foo = 1 })); } }
public void It_Should_Not_Render_If_Partial_Doesnt_Exist_In_Loader() { var stubble = new StubbleBuilder() .SetPartialTemplateLoader(new DictionaryLoader(new Dictionary<string, string> { {"foo", "{{Foo}} this"} })).Build(); var output = stubble.Render("{{> foo2}}", new { Foo = "Bar" }); Assert.Equal("", output); }
public void It_Should_Be_Able_To_Change_Max_Recursion_Depth() { const string rowTemplate = @" <div class='row'> {{#content}} {{#is_column}} {{>column}} {{/is_column}} {{/content}} </div>"; const string columnTemplate = @" <div class='column'> {{#content}} {{#is_text}} {{>text}} {{/is_text}} {{#is_row}} {{>row}} {{/is_row}} {{/content}} </div>"; const string textTemplate = @" <span class='text'> {{text}} </span>"; var treeData = new { is_row = true, content = new { is_column = true, content = new[] { new { is_text = true, text = "Hello World!" } } } }; var stubble = new StubbleBuilder().SetMaxRecursionDepth(128).Build(); var ex = Assert.Throws<StubbleException>(() => stubble.Render(rowTemplate, treeData, new Dictionary<string, string> { {"row", rowTemplate}, {"column", columnTemplate}, {"text", textTemplate} })); Assert.Equal("You have reached the maximum recursion limit of 128.", ex.Message); }