Solving All Problems With Scriban/C#

Scriban is a .NET templating engine, it's a great choice as a golden hammer. It works well with other golden hammers; duel wielding Scriban in the off-hand.

No alt text provided for this image

I fell in love with the library a few years ago. I don't know which I love best from my NuGet feed: Scriban the templating engine, or Polly the retry library. Oh hang on, yes I do - it's Scriban. But Polly is good too, simplifying retry code. But back to Scriban because it's the star of the show.

This is a short and sweet blog about using Scriban with C#

From its own example, on its github page, it uses HTML to show how it swaps values in text templates. But HTML templating engines are ten a penny, and I use it for everything but HTML. That said, it is a good example: it shows what Scriban does and how it does it. Here's its examples:

Parse a scriban template
var template = Template.Parse("Hello {{name}}!");
var result = template.Render(new { Name = "World" }); // => "Hello World!" 
        
...
The language is very versatile, easy to read and use, similar to?liquid?templates:
var template = Template.Parse(@"
<ul id='products'>
  {{ for product in products }}
    <li>
      <h2>{{ product.name }}</h2>
           Price: {{ product.price }}
           {{ product.description | string.truncate 15 }}
    </li>
  {{ end }}
</ul>
");
var result = template.Render(new { Products = this.ProductList });
        

So as you see it deals with complex objects and iteration and stuff like that. It uses the C# objects you pass in. It has its own little function definition notation, so you can make functions and call them from the template. I have used Scriban to template Yaml property values. Resolving the value at runtime can be good. Here is an example of the kind of way I've used Scriban.

? - command: get-my-api-data
? ? send:
? ? ? method: get
      bearer: '{{Args.Token}}'
? ? ? url: https://{{Args.BaseUrl}}/ApiService/presidents/eisenhower/dogs
? ? ? query:
        - key: year
          value: '{{CsvRow.Year}}'
? ? save:
? ? ? folder: '{{SessionId}}/{{CsvRow.Year}}/EisenhowerDogs'
        

There are plenty of ways to pass the model into the renderer, but around ways it worked I also found a couple of ways that didn't work as I expected. However, passing the model as a dictionary of string to object worked well.

var model = new Dictionary<string, object>();
model.Add("Args", commandArgsDict);
model.Add("CsvRow", csvRowDict);
model.Add("SessionId", sessionId.ToString());

var result = template.Render(model);
        

Scriban is just so handy for some things. Why not just use string.Replace()? To be honest if string.Replace() does what you need then why not? If you need anything slightly more than token replacing, then Scriban's lexer/parser gives latitude. It has too much latitude, I hardly use half its features. It just hasn't let me down when I've needed them.

var template = Template.Parse("{{if CsvRow.Year==1953}}true{{else}}false{{end}}";
var strResult = template.Render(model);

var boolResult = Bool.Parse(strResult);
        

And configuring the output of command line utilities, sometimes as a parameter or configurable somewhere.

var template = Template.Parse("{{CsvRow.Year}}, {{CsvRow.Name}}, {{SessionId}}");
var outputLine = template.Render(model);

Console.WriteLine(outputLine);
        

It's fast too.


Scriban is a creation of Alexandre Mutel, currently at Unity doing things like the Burst compiler (https://xoofx.com/blog/2019/03/28/behind-the-burst-compiler/)

要查看或添加评论,请登录

Matthew Cocks的更多文章

  • Yaml, Fairy Tales and Pesky Squatters

    Yaml, Fairy Tales and Pesky Squatters

    Part two of Automation, Fairy Tales and ASCII Art A blog about writing a fairy tale adventure story, its automation and…

    1 条评论
  • Automation, Fairy Tales and ASCII Art

    Automation, Fairy Tales and ASCII Art

    Joseph Campbell's The Hero's Journey (aka The Monomyth) is one of the best tools I have for creating a fairy tale…

社区洞察

其他会员也浏览了