jinja2 loop.index in templates
Brought to you by:
artyom-beilis
In python template engine "jinja2" have special construction "loop.index" for access iteration value inside foreach loops. It useful for "linkindex" and some "if" template statements.
This simple patch - for adding current iteration value inside loop in output (cppcms_tmpl_cc). It's not ideal, so i provided it "as is" and hope you will correct it for the best.
For using patch - write <% loopindex %> inside <% item %> and <% foreach %> blocks.
Anonymous
cppcms_tmpl_cc.patch
cppcms_tmpl_cc.patch.1
Fix the patch for only the first occurrence of 'foreach' in the stack
cppcms_tmpl_cc.patch.2
Fix typo
Thanks interesting. Can you just provide a sample use-case where it can be interesting? But it seems to me as
good addition.
Also I notices that it would start indexing from 0 maybe I'll do it configurable.
Few things I noticed:
Maybe it would be even better
to have something like
<% foreach foo, loopindex = 1 in bar %>
Would generate index variable loopindex starting from 1
So you can have several loops and use loopindex in other statements
like
<% gt "The row number is {1}" using loopindex %>
And also you would not have to use std::distance that may not be cheap
for non-random-access iterators.
Of course it is more complex change.
sorry for so long absence.. so:
use-case:
<% foreach r in menu %> <% item %>- href="http://sourceforge.net/<%%20r.second%20%>"><% r.first %>
<% end %>
<% end %>
about construction "<% foreach foo, loopindex = 1 in bar %>". we can't ensure that new variable will not override some template variable (or even new variable of outer loop) if we can't make the name of this variable reserved.
it will always be a need in developer's checking (or checking in python translator). but this is a common developer's task.
also, we must assume, that second variable after "," - is a loop index and we must create and increment it. it's not so linguistically obvious for beginners.
originally, in jinja2 solution is - alias on outer loop:
{% for row in table %} {% set rowloop = loop %} {% for cell in row %}what's you opinion?
I had not forgot you...
Just too busy right now to review the situation.
Drop me mail in a week or two if I do not respond.
Implemented rowid support in trunk in little bit different way:
http://art-blog.no-ip.info/wikipp/en/page/cppcms_1x_templates_flow#Foreach.block
changeset 1948.