Template for loop and separator

240 views
Skip to first unread message

Ken

unread,
Feb 5, 2012, 9:12:49 PM2/5/12
to python-...@googlegroups.com
Hi,all

Sometime I need template result like:
[1,2,3,4]

{
'a',
'b',
'c'
}

(there is no more comma after the last element)

Normally, we use template like below:
{% for item in items %}
{{ escape(item) }},
{% end %}

It's not worked.

I know str.join function work fine in these situations. My question is:
Is there any solution in Template?

google-ctemplate solution:
http://ctemplate.googlecode.com/svn/trunk/doc/reference.html#separator

Thanks

-Ken

Alek Storm

unread,
Feb 5, 2012, 9:39:18 PM2/5/12
to python-...@googlegroups.com
If {{','.join(items)}} works fine, why do you need something else? Also, values are auto-escaped as of Tornado 2.0; there's no need to explicitly call escape().

Alek

Felinx Lee

unread,
Feb 5, 2012, 9:40:03 PM2/5/12
to python-...@googlegroups.com
{{ escape(“,”.join(items)) }}

Does this work?

--
What can change the nature of a man?(Planescape Torment)
----------------------------------------------------------------------------------------
http://feilong.me            Felinx Lee's Blog (Chinese Only)
http://www.zhimaq.com IT Q&A (Chinese Only)
http://poweredsites.org  What powered your sites? PHP, Ruby or Python?

Matt Ferguson

unread,
Feb 5, 2012, 9:41:38 PM2/5/12
to python-...@googlegroups.com
It sounds like you might be trying to use this in JavaScript, in which case you're better off using json_encode.

Ken

unread,
Feb 5, 2012, 11:28:30 PM2/5/12
to python-...@googlegroups.com
Thanks to Alek, Felinx, Matt

These are not template solution.

Sometimes there are too much code for process looped item, str.join
maybe is not the best solution.

Please take a look google-ctemplate separator[1]:
{{#ATTENDEES}}
{{NAME}}
{{#ATTENDEES_separator}}, {{/ATTENDEES_separator}}
{{/ATTENDEES}}

I wrote huge mount of templates in ctemplate format, the separator is
very useful.

1: http://ctemplate.googlecode.com/svn/trunk/doc/reference.html#separator

-Ken

Ben Darnell

unread,
Feb 6, 2012, 2:10:23 AM2/6/12
to python-...@googlegroups.com
Tornado templates let you write arbitrary python code, so you can do
things like this without specialized support from the template
language itself. For example, you could do:

{% for i, attendee in enumerate(attendees) %}
{{ attendee.name }}{% if i != len(attendees) %}, {% end %}
{% end %}

You could also write an enumerate-like ui_method that would let you
test whether you're on the last element of a list in a less clunky
way.

-Ben

Ken

unread,
Feb 6, 2012, 2:49:16 AM2/6/12
to python-...@googlegroups.com
This way help:

{% if i != len(attendees) %}, {% end %}

Thanks Ben
Thanks to everyone

Reply all
Reply to author
Forward
0 new messages