A macro is a piece of code given a name so it can be called from another part of the template. To declare a macro you use the macro instruction. For example:
{% macro title %}A beautiful book{% end %}
defines a macro named title. A macro is a function, so to call it you use parentheses ( and ):
{{ title() }}
A beautiful book
Inside a macro, you can access not only global variables, but also variables and macros declared earlier in the same file. For example:
{% var prodotto = "tablet" %}
{% macro title %}A beautiful {{ prodotto }}{% end %}
{{ title() }}
A beautiful tablet
A variable declared inside a macro is not visible outside the macro itself.
If a macro has no parameters and there are no other instructions after the macro declaration, you can omit {% end %} or {% end macro %} at the end. The macro ends at the end of the file.
Endless macros are written without the macro keyword and with a capitalized first letter:
{% Main %}
In the following example, Main is an endless macro and therefore extends to the end of the file.
{% extends "layout.html" %}
{% Main %}
<ul>
{% for product in products %}
<li><a href="{{ product.URL }}">{{ product.Name }}</a></li>
{% end for %}
</ul>
The previous example is equivalent to writing
{% extends "layout.html" %}
{% macro Main %}
<ul>
{% for product in products %}
<li><a href="{{ product.URL }}">{{ product.Name }}</a></li>
{% end for %}
</ul>
{% end macro %}
A macro can have parameters, like any other function. These are declared inside parentheses ( and ), separated by a comma ,, and in addition to the parameter name you must specify the type.
The following instruction declares a macro named image with three parameters.
{% macro image(url string, width int, height int) %}
<img src="{{ url }}" width="{{ width }}" height="{{ height }}">
{% end %}
A macro must be called with the same number of arguments, in the same order and of the same type as the parameters in its declaration.
{{ image("picture.jpg", 400, 500) }}
<img src="picture.jpg" width="400" height="500">
A type can be omitted if the next parameter has the same type. The previous declaration can therefore be rewritten as:
{% macro image(url string, width, height int) %}
<img src="{{ url }}" width="{{ width }}" height="{{ height }}">
{% end %}
The syntax for macro arguments is the same as Go functions, with the only difference that macros do not have return parameters.
To call a macro declared in another file, such as a file that declares macros used in various parts of the template, you must first import the file with the import instruction.
{% import "/imports/images.html" %}
{{ Image("offer.png", 200, 200) }}
<img src="offer.png" width="200" height="200">
Macros declared in other files must have a capitalized first letter in their name in order to be imported.