Skip to content

Templates _ TemplateFormatter

axunonb edited this page Mar 30, 2022 · 7 revisions

TemplateFormatter allows you to register reusable templates which contain literal text and placeholders, and include the templates by their name.

Syntax Details

{ Any Value : template(option) }

or

{ Any Value : template : option }

Value formatter name option
Any value "t" name of the template to use

Configuration:

string Name: default is t
The name to use a named formatter

void Register(string templateName, string template): Register a template with its name

public bool Remove(string templateName): Remove a template by its name

public void Clear(): Clear all templates

How to Use The TemplateFormatter

When adding a template, it will be parsed immediately.

Best practice step by step:

1. Have a formatter
var formatter = Smart.CreateDefaultSmartFormat();
2. Create a TemplateFormatter object.
var templates = new TemplateFormatter();
3. Add the TemplateFormatter to the formatter extensions
formatter.AddExtensions(templates);
4. Finally register the templates
templates.Register("SomeTemplate", "The template content: {variable}");

Registering Templates

var templates = new TemplateFormatter();
// Use static default formatter
Smart.Default.AddExtensions(templates);

// ConditionalFormatter with arg1 
// controls the kind of salutation
templates.Register("salutation", "{1:cond:{:t:sal_formal}|{:t:sal_informal}}");
// Register the formal nested template
templates.Register("sal_formal", "Dear Mr {LastName}");
// Register the informal nested template
templates.Register("sal_informal", "Hi {Nickname}");

Using Registered Templates

var person = new 
  { 
    FirstName = "Joseph", 
    Nickname = "Joe", 
    LastName = "Doe" 
  };

// Use the "master" template with different args

// Informal
Smart.Format("{0:t(salutation)}:", person, false);
// Outputs "Hi Joe:"

// Formal
Smart.Format("{0:t(salutation)}:", person, true);
// Outputs "Dear Mr Doe:"
Clone this wiki locally