21

私は Jinja2 ディクショナリを持っており、コンテンツを変更するか、別のディクショナリとマージすることによって、それを変更する単一の式が必要です。

>>> import jinja2
>>> e = jinja2.Environment()

dict の変更: 失敗します。

>>> e.from_string("{{ x[4]=5 }}").render({'x':{1:2,2:3}})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "jinja2/environment.py", line 743, in from_string
    return cls.from_code(self, self.compile(source), globals, None)
  File "jinja2/environment.py", line 469, in compile
    self.handle_exception(exc_info, source_hint=source)
  File "<unknown>", line 1, in template
jinja2.exceptions.TemplateSyntaxError: expected token
                                            'end of print statement', got '='

2 段階の更新: 余分な「なし」を出力します。

>>> e.from_string("{{ x.update({4:5}) }} {{ x }}").render({'x':{1:2,2:3}})
u'None {1: 2, 2: 3, 4: 5}'
>>> e.from_string("{{ dict(x.items()+ {3:4}.items()) }}").render({'x':{1:2,2:3}})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "jinja2/environment.py", line 868, in render
    return self.environment.handle_exception(exc_info, True)
  File "<template>", line 1, in top-level template code
TypeError: <lambda>() takes exactly 0 arguments (1 given)

使用dict(x,**y): 失敗します。

>>> e.from_string("{{ dict((3,4), **x) }}").render({'x':{1:2,2:3}})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "jinja2/environment.py", line 868, in render
    return self.environment.handle_exception(exc_info, True)
  File "<template>", line 1, in top-level template code
TypeError: call() keywords must be strings

x属性を変更したり、別の辞書とマージしたりして、Jinja2の辞書を変更するにはどうすればよいでしょうか。

この質問は次のようなものです: 2 つの Python 辞書を単一の式としてマージするにはどうすればよいですか? -- Jinja2 と Python が類似している限り。

4

3 に答える 3

29

Jinja2 の"do" ステートメント拡張機能が役立つようです。この拡張機能を有効にすると、次のように書き換えることができます。

{{ x.update({4:5}) }} {{ x }} 

なので

{% do x.update({4:5}) %} {{ x }}

例:

>>> import jinja2
>>> e = jinja2.Environment(extensions=["jinja2.ext.do",])
>>> e.from_string("{% do x.update({4:5}) %} {{ x }}").render({'x':{1:2,2:3}})
u' {1: 2, 2: 3, 4: 5}'
>>> 
于 2010-08-13T19:03:48.503 に答える
6

辞書をマージするためのフィルターを追加しました。つまり、次のとおりです。

>>> def add_to_dict(x,y): return dict(x, **y)
>>> e.filters['add_to_dict'] = add_to_dict
>>> e.from_string("{{ x|add_to_dict({4:5}) }}").render({'x':{1:2,2:3}})
u'{1: 2, 2: 3, 4: 5}'
于 2010-04-24T03:21:53.390 に答える