Symfony and Twig: how to check if flash messages are not empty

When rendering Symfony twig templates sometimes you might need to show one html element and hide another element depending if you have flash error/notice messages or not. For example if you have a page with registration form you might want to hide the form if it was submitted successfully and you only want to display a success message. For that you will need to check if the flash messages set by your controller are empty or not.

You can do this by using the app.session.flashBag.has method. Simple example:

{% if app.session.flashBag.has('success_messages') %}
    {% for message in app.flashes('success_messages') %}
        {{ message }}
    {% endfor %}
{% else %}
    Display something else.
{% endif %}

Leave a Reply

Your email address will not be published. Required fields are marked *