Search code examples
pythonjsonjinja2flask-restful

What is the idiom for `flash('Helpful Message')` when one is sending/receiving JSON?


In base.html of my Jinja2 HTML template files I have

{% for message in get_flashed_messages() %}
    <div>
        {{ message }}
    </div>
{% endfor %}

This works well. Wherever I have

from flask import render_template

@main.route('/', methods=['GET', 'POST'])
def index():
    if is_invalid():
        flash('Invalid')
    return render_template('index.html')

the file index.html is returned and the appropriate flashed messages appear, because index.html is derived from base.html.

It get slightly more complicated if I am not updating the entire page. The file details.html, which is still derived from base.html, is too expensive to redraw. When the user triggers an event, a (JSON) API call is received by the server, and the response is interpreted in JavaScript to update (parts of) details.html.

I'd rather not reinvent the wheel. What is the appropriate idiom for flash('Helpful Message') when one is sending/receiving JSON?


Solution

  • you would need to do it in javascript not jinja

    often you will create an "error" div at the top

    <div class="error" id="errorMessage"></div>
    

    then you will populate it on response

    fetch(someurl).then(r=>r.json()).then(data=>{
        document.getElementById("errorMessage").innerText = "Helpful message"
    })
    

    of coarse you might be able to just get away with alert("Helpful Message") or you may want to go with some (javascript) UI library that provides a simple and more robust alert messaging system