Search code examples
pythonflaskjinja2flash-message

Flask: show flash messages in alertbox


I've been working on flask and I came across flash. It displays a message on page if flash was called on the server side. However, I'd like to display the contents get_flashed_messages() in an alertbox. I tried to make JS function and pass {{message}} but the loop prints the call i.e. takes the call as a string.

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

IS there any way to go about it?


Solution

  • You can create JS variable containing messages

    {% with messages = get_flashed_messages() %}
      {% if messages %}
        <script>
          var messages = {{ messages | safe }};
          for (var i=0; i<messages.length; i++) {
            alert(messages[i]);
          }
        </script>
      {% endif %}
    {% endwith %}