9

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'}) %}
Community
  • 1
  • 1
RedBaron
  • 4,717
  • 5
  • 41
  • 65

1 Answers1

5

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).

luke14free
  • 2,529
  • 1
  • 17
  • 25
  • I got the update part (Actually doing it now in {{ }} tags but that prints None). How do I use a {% do %} block. Code will be much appreciated. Espicially how to enable jinja2 extensions from pyramid – RedBaron Jun 15 '12 at 10:05