import
construct
The import
tag is the way to reuse defined macros, it affects the model, adding a variable containing all macros defined in a specific Jtwig template resource.
{% import resourcePath as macros %}
As shown in the previous example, all macro definitions inside resourcePath
will be amalgamated in the macros
variable, so called the alias.
How to use?
To call a macro, one just need to use the alias together with the desired macro name and its arguments.
{{ macros.macroName(argument1, argument2) }}
Let's then have a look to the example below.
File: forms.twig
{% macro text (name, defaultValue) %}
<input name="{{ name }}" type="text" value="{{ defaultValue }}" />
{% endmacro %}
File: template.twig
{% import 'forms.twig' as forms %}
{{ macros.text('username') }}
As one can see from the previous example, the template template.twig
imports all macro definitions from forms.twig
into the alias forms
. It then renders the text
macro providing only one argument 'username'
.
Argument resolution
As mentioned before, macro arguments are all optional. In the previous example, the macro defined two arguments name
and defaultValue
, however the call only provided one argument. The way arguments are feeded into the macro is by the order specified. In the previous example, the provided argument 'username'
will then be represented by the identifier name
in macro specification.