dict() function in Tornado Templates.

845 views
Skip to first unread message

Zippoxer

unread,
Mar 14, 2011, 2:44:12 PM3/14/11
to Tornado Web Server
Jinja2 has dict() function which creates a dictionary (which can be
iterated): http://jinja.pocoo.org/docs/templates/#dict
Tornado templates has list() only but dict() is missing.
Can tornado templates create a dictionary? And if they can't, how can
I add this functionality?

Zippoxer

unread,
Mar 14, 2011, 2:55:03 PM3/14/11
to Tornado Web Server
Okay. There is some kind of solution.

I noticed I can do this:
{% for k, v in [("Name", current_user), ("Level", "1"), ("City",
"Carlin"), ("Health", "100/100"), ("Mana", "100/100")] %}
{{ k }} = {{ v }}<br/>
{% end %}

But not this:
{% for k, v in [("Name", current_user),
("Level", "1"), ("City", "Carlin"),
("Health", "100/100"),
("Mana", "100/100")] %}
{{ k }} = {{ v }}<br/>
{% end %}

Conclusion: I must write all of the elements in one line :\

Ben Darnell

unread,
Mar 14, 2011, 2:58:12 PM3/14/11
to python-...@googlegroups.com, Zippoxer
All built-in python functions (including list() and dict()) are accessible in tornado templates.  To add new functions to the template namespace, you can use the ui_methods application setting or pass keyword arguments to the render method.

-Ben

Zippoxer

unread,
Mar 14, 2011, 3:22:18 PM3/14/11
to Tornado Web Server
This doesn't work :(
Tornado templates doesn't support named parameters? (So I can't create
a dict(key="value"))

Ben Darnell

unread,
Mar 14, 2011, 4:02:47 PM3/14/11
to python-...@googlegroups.com, Zippoxer
Tornado templates mostly just get turned into python code, so whatever works in python should work in the template (including named parameters, etc).  You'll need to provide more information about what's not working.

-Ben

Didip Kerabat

unread,
Mar 14, 2011, 4:30:23 PM3/14/11
to python-...@googlegroups.com
this works:

{% for k, v in dict(bro='it works').items() %}
the key: {{ k }}<br/>
value: {{ v }}
{% end %}

- Didip -

Zippoxer

unread,
Mar 15, 2011, 1:15:16 AM3/15/11
to Tornado Web Server
Ohh I forgot you should use .items(), thanks =]

Okay, so this works:
{% for k, v in {"name": current_user, "level": "1", "city": "Carlin",
"health": "100/100", "mana": "100/100"}.items() %}
<tr>
<td class="key">{{ k.title() }}</td>
<td class="value">{{ v }}</td>
</tr>
{% end %}

But this doesn't:
{% for k, v in {"name": current_user,
"level": "1",
"city": "Carlin",
"health": "100/100",
"mana": "100/100"}.items() %}
<tr>
<td class="key">{{ k.title() }}</td>
<td class="value">{{ v }}</td>
</tr>
{% end %}

the {% for %} statement can't be divided to more than one like.
Reply all
Reply to author
Forward
0 new messages