Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
We'll look at writing and using multiple macros.
You may add as many Macros to a file as you want, but it's a good idea to group macros logically.
You can add a second form macro to our forms.twig file:
{% macro textarea(name, value, rows=5, help) %}
<div class="form-group">
<label for="input{{ name }}">{{ name|title }}</label>
{% if help %}<small class="form-text text-muted">{{ help }}</small>{% endif %}
<textarea class="form-control" id="input{{ name }}" name="{{ name }}" placeholder="Enter your {{ name }}" rows="{{ rows }}">{{ value }}</textarea>
</div>
{% endmacro %}
You only need to import the file containing the macro once. Then you may access any macro from that file.
{{ forms.input('name', post.name) }}
{{ forms.textarea('message') }}
Alternatively, you can import individual macro names from a template into the current namespace via the from tag and optionally alias them:
{% from 'forms.twig' import forms as textarea %}
{{ textarea('message') }}
Twig allows you to put the name of the macro after the end tag for better readability:{% endmacro input %}
Of course, the name after the endmacro word must match the macro name.
You need to sign up for Treehouse in order to download course files.
Sign up