Using Scriban to Render Templates in .NET Core

Introduction

There are many scenes that need templates to render text, such as E-mail, SMS, etc.

Sending an SMS verification code is a very common scenario. Login, Register, or other operations may need it for verification, so there will be many templates for SMS verification codes.

For example, here is a message after rendering.

1234 is your Login verification code. [INFO]

The simple solution is to use string. Format.

// read this from database
var tplStr = @"{0} is your {1} verification code.[INFO]";

// generate this value by some rule
var code = "0000";
var module = "Login";

// render it
var res = string.Format(tplStr, code, module);

As we can see in the above sample, there are two placeholders, 0 to specify the code, and 1 to specify the module.

What is going to happen when somebody modifies the value of tplStrto swap the two placeholders?

The result will be,

Login is your 0000 verification code.
[INFO]

The user who receives this SMS will be confused.

In order to solve this problem, we should make the placeholders significant.

The template engine can help us out. Here we take Scriban for example.

Scriban

Scriban is a fast, powerful, safe, and lightweight text-templating language and engine for .NET, with a compatibility mode for parsing liquid templates.

Scriban

Visit its GitHub Page for more information about Scriban.

Continuing with the above sample, how to finish the job with Scriban?

We also should define the template first.

// read this from database
var tplStr = @"{{code}} is your {{module}} verification code.[INFO]";

Not only is the template very easy to understand, but so is the meaning of the two placeholders.

The next step is to parse the template text.

// parse the template text
var tpl = Template.Parse(tplStr);

At last, render the template with a specific value.

// generate this value by some rule
var code = "0000";
var module = "Login";

// render it
var res = tpl.Render(new { code, module });

The following is the complete code fragment.

static void TemplateEngineVersion()
{
    // read this from database
    var tplStr = @"{{code}} is your {{opreation}} verification code.[INFO]";

    // parse the template text
    var tpl = Template.Parse(tplStr);
      
    // generate this value by some rule
    var code = "0000";
    var module = "Login";

    // render it
    var res = tpl.Render(new { code, module });

    Console.WriteLine("=== template engine version ===");
    Console.WriteLine(res);
    Console.WriteLine("=== template engine version ===");
}

And the result for the samples.

Result

Summary

This article showed you that a template engine is helpful when we want to render something. It also introduced the basic usage of Scriban.

I hope this will help you!