pythondictionarypyramidjinja2

Modifying dictionary attributes in jinja2


Suppose I pass a dictionary to my jinja2 template.
In the view I have something like

d = {}
#set other template stuff into d
get_params['cri'] = 'time'
get_params['order'] = 'asc'
d['get_params'] = get_params
return d

In the template I need to change the value of keys of get_params. The logical thing

{% set get_params.cri='src' %}

fails with an error

TemplateSyntaxError: expected token '=', got '.'

My question is how do I modify the values passed to a dictionary in jinja2

(This question has been asked here, but I find the answer confusing and it only answers the merging part)

Answer EDIT:

Jinja2 provides the 'do' extension. To add that extension to pyramid, do the following in the __init__.py file

#This line is alreadythere
config.include('pyramid_jinja2')
#Add this line
config.add_jinja2_extension('jinja2.ext.do')

In the template

{% do get_params.update({'cri':'src'}) %}

Solution

  • The idea is that you cannot perform assignments in jinja2. What you can do however (as suggested in the other post that you linked) is to call a do block and perform an update operation (update is a method of any dict in python; http://docs.python.org/library/stdtypes.html#dict.update).