2

So I write the controller:

@app.route('/')
def index():
    flash('Hello world!', 'success')
    return render_template('index.html')

then in my template I output the flash messages like this:

{%- with messages = get_flashed_messages(with_categories=true) -%}
{%- if messages -%}
    <ul class="flashes unstyled">
    {%- for category, message in messages -%}
        <li class="alert alert-{{ category }}">
            <a class="close" data-dismiss="alert">&times;</a>
            {{ message }}
        </li>
    {%- endfor -%}
    </ul>
{%- endif -%}
{%- endwith %}

But the issue is that I ALWAYS get just 'message' category so <li> goes with classes 'alert alert-message'.
I read the docs and as to me I did everything right, but 'flash' function ignoring the second argument and always uses the default value 'message' (instead of given by me 'success').

I wonder if anyone had that issue and know how to handle it?

rkhayrov
  • 10,040
  • 2
  • 35
  • 40
c00p3r.web
  • 808
  • 3
  • 10
  • 21

2 Answers2

6

Edit: Based on other comments and testing the kwarg is unnecessary.

Based on the docs at http://flask.pocoo.org/docs/api/#message-flashing it appears you need to use this format. flash(message, category='message')

@app.route('/')
def index():
    flash('Hello world!', category='success')
    return render_template('index.html')
Seberius
  • 399
  • 2
  • 6
  • 3
    You don't need to provide a kwarg to it. I use it in the form `flash('message', 'category')` and it works fine. – Joe Doherty Aug 23 '13 at 07:59
  • yep, you don't have to pass key=value pair (though you can). And I tried that already... no results :( – c00p3r.web Aug 23 '13 at 08:32
  • @Joe You are quite right. I just tested it as well in Flask 0.10.1 and it is working properly. – Seberius Aug 23 '13 at 08:32
  • Don't know what happend but with `category='success'` it worked! Hmmm... strange... I'm sure I've tryied that way and it didn't help then. Well, the issue is solved so thank you! – c00p3r.web Aug 23 '13 at 09:13
5

When you call get_flashed_messages(with_categories=True), it return a list of tuples in the form (category, message).

So now you can use flash() like this:

flash('some message', 'success') # `category=` is needn't

In html, you can just loop the message in the call:

{% for message in get_flashed_messages(with_categories=True) %}
<div class="alert alert-{{ message[0] }}">
    <button type="button" class="close" data-dismiss="alert">&times;</button>
    {{ message[1] }}
</div>
{% endfor %}
Grey Li
  • 11,664
  • 4
  • 54
  • 64