richard0096 richard0096 - 3 days ago 5
Python Question

Difficulty understanding Jinja template

Hi I've used a piece of code from the Flask microblog program into my program to display any validation errors that occur (https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-iii-web-forms)

The piece I used was as follows:

{% with messages = get_flashed_messages() %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }} </li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
{% block content %}{% endblock %}


Basically I'm trying to understand which parts of this is gathering errors and how this function actually works so I can personalize it to use it better within my program.

Any help would be greatly appreciate. Thanks!

Answer

Create var named 'messages' with value returned by get_flashed_messages() function.

{% with messages = get_flashed_messages() %}

If messages var list is not empty or None or False value:

{% if messages %}

Create list (li) with each element of 'messages' (messages is list). And display message, equivalent of str(message).

<ul>
{% for message in messages %}
    <li>{{ message }} </li>
{% endfor %}
</ul>
{% endif %}

End of scope for var 'messages'. After this tag, 'messages' var doesn't exist.

{% endwith %}

Block named 'content' for injection in parent template.

{% block content %}{% endblock %}
Comments