Use Mustache template string in .net program

Today get a configuration with the use of dynamic switching function of the environment, the basic idea is:

  1. The configuration is a form template,
  2. Depending on the environment define environment variables
  3. According to the template rendering environment variables, generate specific configuration

There lies a string functions related to the template, the template on grammar, I chose the more popular recently "Mustache" grammar, basic format is a text-based interpolation double braces,

    <span>Message: {{ msg }}</span>

Mustache is characterized by relatively simple to use and easy to read, even if the operation and maintenance personnel is not difficult to understand and use.

As to the realization, in itself just to implement a simple brace interpolation is relatively simple to achieve their own did a few lines of code, but taking into account future extensibility, or supports the full Mustache grammar engine of it, the official C # parser library is stubble , a basic example is as follows:

    var stubble = new StubbleBuilder().Build();
    var output = stubble.Render("hi {{name}}", new {name = "world"});

Dictionary type can accept as a parameter, very convenient.

    var output = stubble.Render("hi {{name}}",
        new Dictionary<string, object>()
        {
              ["name"] = "world"
        });

Other examples not presented here, if interested can view their official example .

Another popular Mustache library is Nustache , the volume should be smaller, the interface should be simple point,

    var output = Render.StringToString("hi {{name}}", new {name = "world"});

But it has two problems.

  1. But it does not .net core version, with just a portable version nustache.core , also 3 years ago
  2. It is no syntax checking stubble strict, such as rendering "" hi {{name}} "" such an error template does not throw an exception, and given the wrong rendering results. The stubble will complain,

For these two reasons, I think it is the official recommendation of stubble more appropriate.

In addition, I am in search string template when found another popular template Liquid , syntax works very similar

    Template template = Template.Parse("hi {{name}}"); // Parses and compiles the template
    template.Render(Hash.FromAnonymousObject(new { name = "tobi" })); // => "hi tobi"

Interested friends can refer to the following article: DotLiquid template engine Introduction

 

Guess you like

Origin www.cnblogs.com/TianFang/p/11915101.html