Python, Flask, and jinja templates - How to iterate over a dictionary created server side

10,635

Solution 1

You need to pass creative_handler to the template:

return render_template("edit_creatives.html", title='Edit Creative', creative_handler=creative_handler)

Solution 2

Well you need to pass in the variable(s) you want to use, in the template.

>>> from flask import render_template
>>> help(render_template)
render_template(template_name, **context)
    Renders a template from the template folder with the given
    context.

    :param template_name: the name of the template to be rendered
    :param context: the variables that should be available in the
                    context of the template.

so return render_template("edit_creatives.html",title = 'Edit Creative', creative_handler = creative_handler)

Share:
10,635
Tampa
Author by

Tampa

Updated on June 05, 2022

Comments

  • Tampa
    Tampa almost 2 years

    I am using flask.

    On the server server when a page loads I create a dictionary.

    @app.route('/edit_creative', methods=["GET", "POST"])
    @login_required
    def edit_creative():
        if request.method == "POST": 
            pass
    
        query = """select * from mystable"""
        print query
        rows = execute_query(query,select=True)
        creative_handler={}
        for row in rows:
            j = row[2].strip("'")
            j = json.loads(j)
            creative_handler[row[1]]=j
    
        return render_template("edit_creatives.html",title = 'Edit Creative')
    

    On the client side I want to iterate over the hash:

    {% for crid, object in creative_handler.iteritems() %}
    
    {{ crid }}<br>
    
    {% endfor %}
    

    On the page I get this error

    UndefinedError: 'creative_handler' is undefined
    

    So..how do I use jinja templates to iterate over a hash creates server side?