Kentico CMS 7.0 Developer's Guide

Types of macros

Types of macros

Previous topic Next topic Mail us feedback on this topic!  

Types of macros

Previous topic Next topic JavaScript is required for the print function Mail us feedback on this topic!  

The macro type is determined by the character at the beginning and end of the macro. Macros look like:

 

{<type character><expression><parameters><type character>}

 

Where the type character can be one of the following:

 

% - Context (data) macro

$ - Localization macro

? - QueryString macro

@ - Cookie macro

^ - Control macro

& - Path macro

# - Custom macro

~ - Substitution macro

 

Macros of the same type can be nested using the "index parentheses" syntax, e.g. {(1)%FullName|(default){(2)%Username%(2)}%(1)}. Click particular macro types in the listing above to get redirected to their detailed explanation.

 

Context (data) macros

 

This type of macros evaluates data based on current context. These macros can be used for example to parametrize web parts' parameters with current document or user values. These macros can be used in combination with the K# language. For more information on its syntax and possibilities, please refer to the K# syntax and Available macro methods topics.

 

The format of the macro is {%ColumnName%} and the value is replaced with the appropriate value of the column based on current context. You can use all column names from current site data, current user data and current document data.

 

Example: “Welcome {%FullName%}” will be resolved as “Welcome Global administrator” when the administrator is the current user.

 

There are also data macros with selectors to precisely identify the source of the data, these macros look like {%CurrentDocument.DocumentName%} and can be used for accurate determination of the data source. Availability of the selectors depends on the context where the macros are evaluated.

 

Localization macros

 

These macros are usually used on multilingual websites to help localize system strings. There are two types of localization macros:

 

Basic

 

Basic localization macros are entered in format {$string.key$}. Alternatively, you can enter them as context macros in the {% GetResourceString("resourcestring.key") %} format. The system uses the ResHelper.GetString(“string.key”) method and replaces the macro with the appropriate language version of the given resource string.

 

Example: "The weather is {$General.OK$}" is resolved as "The weather is OK".

 

In-place localization

 

You can include the string and its localized equivalents directly within the macro. Such macros are entered in format {$=Default string|cs-cz=Czech string|de-de=German string$}. They either return a localized string for the current language, or the default (first) string if a matching localized value is not available.

 

Example: "The weather is {$=OK|cs-cz=dobre|de-de=gut$}” is resolved into “The weather is dobre” in the Czech culture, “The weather is gut” in the German culture and “The weather is OK” in any other culture.

 

QueryString macros

 

These macros evaluate querystring parameters information. These macros can be used for example to dynamically parameterize the controls by the querystring parameters.

 

The macros are entered in the {?querystring_key?} format. Alternatively, you can also enter them as data macros like the following: {%QueryString.querystring_key%}. The macro is replaced by the querystring parameter value.

 

Example: “Current node ID: {?nodeid?}” will be resolved as “Current node ID: 10” for a URL like “default.aspx?nodeid=10

 

Cookie macros

 

These macros evaluate the values of the current user's browser cookies. For example, these macros can be used to parametrize web parts using client-based persistent values like styles or user options.

 

The macro is entered in format {@cookie_name@}. Alternatively, you can also enter them as data macros like the following: {%Cookies.cookie_name%}. The macro is replaced by the given cookie's value.

 

Example: “Current style: {@StyleCookie@}” will be resolved as “Current style: Red” if the StyleCookie value is set to “Red

 

Control macros

 

These macros are resolved into inline controls, which can be used to place dynamic content into editable text regions and HTML layouts. The macros are specified in format {^BizFormControl^} and can (usually must) contain parameters for the control using standard parameterized macro syntax, such as {^BizFormControl|(FormName)ContactForm^}. The parameters will be used to initialize the control when the macro is resolved.

 

Path macros

 

These macros are entered in the {&path&} format. Alternatively, you can also enter them as data macros like the following: {%Path.path%}. They can be used to resolve current document Alias path the same way as the Path property of controls. The macro is replaced by the resolved path.

 

Example: WhereCondition: NodeAliasPath LIKE {&../%&}. In this case, the macro is resolved as the path of the parent document and results in selecting all siblings of the current document and their child documents. This macro is intended mostly for including the document structure context into the controls WHERE condition, but can be used for many more purposes.

 

See Appendix A - Path expressions for more details on how paths can be entered.

 

Custom macros

 

Custom macros allow you to define your own macro expressions. Their basic format is: {#Expression#}. Alternatively, you can also enter custom macros as data macros with the Custom. prefix: {%Custom.Expression%}.

 

Defining custom macros

 

When a custom macro needs to be resolved, the system calls the methods registered as handlers for the MacroResolver.OnResolveCustomMacro event. To create a new custom macro, you must implement a handler method that ensures the resolving of individual expressions into the appropriate results.

 

1. Open your web project in Visual Studio and add a new class into the App_Code folder (or Old_App_Code if the project is installed as a web application). For example, name the class CustomMacroLoader.cs.

 

2. Edit the class and add the following references:

 

[C#]

 

using CMS.SettingsProvider;
using CMS.GlobalHelper;

 

3. Delete the default class declaration and its content. Instead, extend the CMSModuleLoader partial class and define a new attribute:

 
[C#]

 

[CustomMacroLoader]
public partial class CMSModuleLoader
{
    /// <summary>
    /// Attribute class ensuring the registration of macro handlers.
    /// </summary>
    private class CustomMacroLoader : CMSLoaderAttribute
    {
        ...
    }
}

 

4. Enter the following code into the CustomMacroLoader attribute class:

 

[C#]

 

/// <summary>
/// Called automatically when the application starts.
/// </summary>
public override void Init()
{
    // Assigns a custom macro resolving handler.
    MacroResolver.OnResolveCustomMacro += MacroResolver_OnResolveCustomMacro;
}
 
 
/// <summary>
/// Resolves custom macros.
/// </summary>
/// <param name="sender">Sender</param>
/// <param name="e">Event arguments representing the resolved macro</param>
private void MacroResolver_OnResolveCustomMacro(object sender, MacroEventArgs e)
{
    // Checks that the macro is not resolved yet.
    if (!e.Match)
    {
        // Defines the return values of specific custom macro expressions.
        switch (e.Expression.ToLower())
        {
            // Handles the {#CustomExpression#} macro.
            case "customexpression":
                e.Match = true;
                e.Result = "Resolved expression";
                break;
        }
    }
}

 

The override of the Init method registers the MacroResolver_OnResolveCustomMacro method as a handler for the OnResolveCustomMacro event.

The MacroResolver_OnResolveCustomMacro method defines the return value of the custom expression. The sample code only assigns a string constant as the macro result, but you may add any required API logic to set the value dynamically. You can create any number of custom macros by adding further cases into the switch statement.

 

The system now recognizes the {#CustomExpression#} macro and resolves it into the Resolved expression string.

 

Substitution macros

 

Substitution macros are entered in format {~expression~}. They are similar to Custom macros. The difference is that the system resolves substitution macros in page output code, i.e. the page's final code before it is sent to the browser for rendering. The main advantage of substitution macros is that they are resolved on each request, even for pages that use full-page caching.

 

Defining substitution macros

 

When a substitution macro needs to be resolved, the system calls the methods registered as handlers for the OutputFilter.OnResolveSubstitution event. To create a new substitution macro, you must implement a handler method that ensures the resolving of individual expressions into the appropriate results.

 

1. Open your web project in Visual Studio and add a new class into the App_Code folder (or Old_App_Code if the project is installed as a web application). For example, name the class CustomMacroLoader.cs.

 

2. Edit the class and add the following references:

 

[C#]

 

using CMS.SettingsProvider;
using CMS.GlobalHelper;
using CMS.CMSOutputFilter;
using CMS.OutputFilter;

 

3. Delete the default class declaration and its content. Instead, extend the CMSModuleLoader partial class and define a new attribute:

 
[C#]

 

[CustomMacroLoader]
public partial class CMSModuleLoader
{
    /// <summary>
    /// Attribute class ensuring the registration of macro handlers.
    /// </summary>
    private class CustomMacroLoader : CMSLoaderAttribute
    {
        ...
    }
}

 

4. Enter the following code into the CustomMacroLoader attribute class:

 

[C#]

 

/// <summary>
/// Called automatically when the application starts.
/// </summary>
public override void Init()
{
    // Assigns a substitution macro resolving handler.
    OutputFilter.OnResolveSubstitution += OutputFilter_OnResolveSubstitution;
}
 

 
/// <summary>
/// Resolves output substitution macros.
/// </summary>
/// <param name="sender">Sender</param>
/// <param name="e">Event arguments representing the resolved macro</param>
private void OutputFilter_OnResolveSubstitution(object sender, SubstitutionEventArgs e)

{
    // Checks that the macro is not resolved yet.
    if (!e.Match)
    {
        // Defines the return values of specific substitution macros.
        switch (e.Expression.ToLower())
        {
            // Handles the {~CustomSubstitution~} macro.
            case "customsubstitution":
                e.Match = true;
                e.Result = "Resolved substitution";
                break;
        }
    }
}

 

The override of the Init method registers the OutputFilter_OnResolveSubstitution method as a handler for the OnResolveSubstitution event.

The OutputFilter_OnResolveSubstitution method defines the return value of the custom expression. The sample code only assigns a string constant as the substitution result, but you may add any required API logic to set the value dynamically. You can create any number of substitution macros by adding further cases into the switch statement.

 

The system now recognizes the {~CustomSubstitution~} macro and resolves it into the Resolved substitution string.