Skip to content
JPVenson edited this page May 10, 2022 · 10 revisions

Morestachio has Build in support for variables. There are two different kinds of variables: #var and #let. #var creates an global variable that is accessible everywhere #let creates a variable that is only accessible within the scope it is declared

Example: {{#var name = "test"}} this will create the global variable name with the string value of "test".

You can use the variable in any expression and Formatter. To overwrite a global variable just set it again. Example:

{{name}}              <- the string representation of the null value
{{#var name = "test"}}
{{name}}              <- test
{{#var name = 123}}
{{name}}              <- 123
{{#var name = data.AnyValue}}
{{name}}              <- whatever is in data.AnyValue
{{#var name = null}}
{{name}}              <- the string representation of the null value

Variables and Alias are the same and an Alias can be overwritten by creating an Variable that has the same name

Example:

{{#each Data.Values AS val}}
    {{val}}               <- Value of val
    {{#var val = "test"}}
    {{val}}               <- test
{{/each}}

A variable created with the #let syntax is only valid inside its enclosing scope but an variable created on the top most level is handled as it was created with the #var syntax.

Example:

{{#let value = "testA"}}
{{value}}                     <- "testA"
{{#each Data.Values AS innerValue}}
    {{value}}                 <- "testA"
    {{innerValue}}            <- Value of innerValue
    {{#var innerValue = "test"}}
    {{innerValue}}            <- test
    {{#let value = innerValue}}
    {{value}}                 <- test
{{/each}}
{{value}}                     <- "testA" again

Capture variables

To get all variables you have set from your template, you have to enable the MorestachioDocumentInfo.CaptureVariables flag. The MorestachioDocumentInfo is returned if you call ParserOptions.ParseWithOption(...) or ParserOptionsBuilder.BuildAndParse(). If set, all variables of an execution will be stored within the MorestachioDocumentResult.CapturedVariables