Advanced template writing

Learn how to write advanced templates on Butly.co

The basic thing to know when writing a template is that you can declare variables by using the brackets In his guide, you will see that we can go further.

We use Jinja as a template engine, which means that you can use all the features of the jinja engine. Do not hesitate to consult their documentation.

Writing advanced template requires manipulating HTML code. To do that easily, switch to the code editor:

Jinja2 integrates two control structures: the loop and the conditional test.

The loop

You can declare a loop with the following syntax

{% for ... in ... %} ... {% endfor %}

For example, suppose contacts contains a list of contacts, you can loop over the contacts like this:

    {% for contact in contacts %}
    <tr>
        <td>{{contact.first_name}}</td>
        <td>{{contact.last_name}}</td>
    </tr>
    {% endfor %}

The conditional test

You can declare a conditional test with the following syntax

{% if ... %} ... {% else %} ... {% endif %}

For example, suppose condition is your variable you want to test, you can render different HTML code depending on the condition value:

    {% if condition %}
        <div>blah blah</div>
    {% else %}
        <div>bloh bloh</div>
    {% endif %}

Last updated

Was this helpful?