► ExamplesAPIMacro engine

Macro engine examples

On this page, you can find examples of the Kentico macro language (K#). For detailed documentation of the macro engine and syntax of the K# language, see Macro expressions.

  • K# is case insensitive. The following macros return the same value.

    {% currentpageinfo.documentname %} -> Macro engine
    {% CurrentPageInfo.DocumentName %} -> Macro engine

  • You can use C#-like syntax to concatenate strings, perform arithmetic operations, access items through indexes, and more:

    {% "MyPrefix" + CurrentPageInfo.DocumentName %} -> MyPrefixMacro engine
    {% 2 * 3 - 5 %} -> 1
    {% CurrentDateTime.Year %} -> 2018
    {% "Test"[2] %} -> s

  • Macros provide a large number of predefined methods (for a complete list, please see Reference - Macro methods):

    {% CurrentPageInfo.DocumentName.ToUpper() %} -> MACRO ENGINE
    {% ToUpper(CurrentPageInfo.DocumentName) %} -> MACRO ENGINE
    {% CurrentPageInfo.DocumentName.Substring(0,5) %} -> Macro
    {% Substring(CurrentPageInfo.DocumentName, 0, 5) %} -> Macro

  • K# supports compound expressions and variable declaration. The scope of a variable declaration is the whole object containing the macro (document, transformation, e-mail template, etc.). The result of the compound expression is the result of the last expression.

    {% x = 10; x %} -> 10

  • K# supports flow control commands such as conditional statements and loops:

    {% result = 0; i = 0; while (i < 10) {if (i > 3) { break; }; result += i; i++; }; result %} -> 6
    {% z = ""; foreach (x in "test") { z += x.toupper() }; z %} -> TEST
    {% z = 0; for (i = 0; i < 5; i++) { z += 1 }; z %} -> 5

  • You can use Localization macros to insert system strings in one of two formats. Basic localization macros are entered in the { $string.key$} format. This macro loads the value of the specified localization string in the current language. Another option is to define translations for individual languages directly in the macro, for example { $=OK|cs-cz=dobre|de-de=gut $}. The system replaces the macro with "dobre" in the Czech culture, "gut" in the German culture and "OK" in any other culture.