import jinja2
from jinja2 import Template
records = [{'a':1,'b':1, 'c':1},{'a':1,'b':1, 'c':1}, {'a':2,'b':1, 'c':1}, {'a':3,'b':1, 'c':1}]
t = jinja2.Template("""
{% set record_info = dict() %}
{% for item in records %}
{% set key = str(item['a'])+str(item['b'])+str(item['c']) %}
{% if key in record_info %}
{% set record_info.key += 1 %}
{% else %}
{% set record_info.key = 1 %}
{% endif %}
{% endfor %}
{{record_info}}""")
This gives me:
Traceback (most recent call last):
File "<stdin>", line 11, in <module>
File "/Library/Python/2.7/site-packages/jinja2/environment.py", line 945, in __new__
return env.from_string(source, template_class=cls)
File "/Library/Python/2.7/site-packages/jinja2/environment.py", line 880, in from_string
return cls.from_code(self, self.compile(source), globals, None)
File "/Library/Python/2.7/site-packages/jinja2/environment.py", line 591, in compile
self.handle_exception(exc_info, source_hint=source_hint)
File "/Library/Python/2.7/site-packages/jinja2/environment.py", line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File "<unknown>", line 6, in template
jinja2.exceptions.TemplateSyntaxError: expected token 'end of statement block', got '.'
What am I doing wrong ?
I was able to do it like this, any improvements?
records = [{'a':1,'b':1, 'c':1},{'a':1,'b':1, 'c':1}, {'a':2,'b':1, 'c':1}, {'a':3,'b':1, 'c':1}]
t = jinja2.Template("""
{% set record_info = dict() %}
{% for item in records %}
{% set key = item['a'] ~ ':' ~ item['b'] ~ ':' ~ item['c'] %}
{% if key in record_info %}
{% set _dummy = record_info.update( {key: record_info[key]+1 }) %}
{% else %}
{% set _dummy = record_info.update({ key:1 }) %}
{% endif %}
{% endfor %}
{{record_info}}""")
print t.render(records=records)
{u'1:1:1': 2, u'3:1:1': 1, u'2:1:1': 1}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With