macro

Syntax

[#macro macroName(parameters)]
body
[/#macro]

where:


Each parameter is of the form:

name : type

where:

Description

The macro directive defines the signature of a macro, as well as the contents to be generated.

The name of a macro must be unique within its container (template or library). The macro may define expected parameters, used to compute the generated contents. Any caller of the macro must provide matching arguments. The return type does not need to be defined here, as macro always return strings.

A macro is called like regular directives, except that

For example, a macro myMacro is called from a template this way: [@myMacro/].

The predefined variable nested can be used in the macro body. The nested variable will contain the evaluation result of the statements found between the start tag and the end tag of the macro call.

A macro which expects a nested contents is called using start tag and end tag:
[@myMacro]some nested contents[/@myMacro]

Macros can be defined in a text template file, or in a library to be reused in multiple places.

Examples

Macro without parameters

This template uses a macro to print the current date:

[#package com.mycompany.example]

[#macro currentDate]
${java.util.Calendar.getInstance().getTime()}[#rtrim]
[/#macro]

[#template Copyright()]
/**
 * Copyright 2006 My Company, Inc. All rights reserved.
 * [@currentDate/] [#-- call the macro currentDate --]
 */
[/#template]

The above template would produce an output similar to the following:

/**
 * Copyright 2006 My Company, Inc. All rights reserved.
 * Thu Apr 13 14:10:11 CEST 2006
 */

Macro with parameters

This template uses a macro to format a pair of strings:

[#package com.mycompany.example]

[#macro outputAnimal(name : String, size : String)]
    ${name} -> ${size}
[/#macro]

[#template Generate()]
Animals:
[@outputAnimal("Mouse", "Small")/]
[@outputAnimal("Elephant", "Huge")/]
[/#template]

The above template will produce the following output:

Animals:
    Mouse -> Small
    Elephant -> Huge

Macro with nested

This template uses a macro to comment a section of text:

[#package com.mycompany.example]

[#macro comment]
[#-- 'nested' contains the text between the start tag and end tag in the macro call --]
[#-- This code just put '//' at the beginning of each line --]
//${nested.replaceAll("\\n", "\n//")}
[/#macro]

[#template Generate()]
[@comment]This text
will be
commented[/@comment]
[/#template]

The above template will produce the following output:

//This text
//will be 
//commented

Related concepts
Macro