[Flask] Passing a JSON array via **templateData in render_template

ub at artfacts.net ub at artfacts.net
Sat Nov 19 07:16:27 EST 2016


hello john,

entries is not really JSON, it is a dict, so it needs need to be
stringified it before being passed it into templates.
use json.dumps or flask.jsonify
when embedding JSON in jinja2 templates, remember to use the "safe"
filter, or you will get unexpected results.

cheers,
ub

On 18.11.2016 21:32, John Overbaugh wrote:
> I created a 3-item JSON object (an array of items) and want to reference
> it via javascript in my main.html page. I also have other template data
> I wish to send (a nonce, a title, etc.). 
> 
>   * When I exclude the JSON object, everything renders fine, but as soon
>     as I add the JSON object to templateData, I get a TypeError that
>     render_template() takes exactly one argument.
>   * If I render_template with just the JSON object, the page renders OK
>     (just missing the other data I want to have available like title and
>     script_nonce)
> 
> 
> Am I just missing something that's totally obvious, or is it not
> possible to pass a JSON array along with other templateData?
> 
> entries = [
>         {
>             'id': 1,
>             'session': 1392596278493910,
>             'time': '201611161227',
>             'from': 'Device123',
>             "Message1": "Hello, my name is Billy",
>         },
>         {
>             'id': 2,
>             'session': 1392596278493910,
>             'time': '201611161229',
>             'from': 'Tom1',
>             'Message': 'Hello Billy, my name is Tom Riddle',
>         },
>         {
>             'id': 3,
>             'session': 1392596278493910,
>             'time': '201611161244',
>             'from': 'Device124',
>             'Message': 'Do you know Moaning Myrtle?',
>         },
>     ]
> 
> @app.route('/', methods=['GET'])
> def hello():
>     # Create a nonce for this page
>     scriptNonce = random.getrandbits(64)
>     
>     templateData = {
>         'title' : 'Tom Riddle Diary',
>         'script_nonce' : scriptNonce,
>         'entry_Collection' : entries
>         }
>     
>     r = make_response(render_template('main.html', **templateData))
>     return r
> 
> 
> _______________________________________________
> Flask mailing list
> Flask at python.org
> https://mail.python.org/mailman/listinfo/flask
> 



More information about the Flask mailing list