【问题标题】:How can I modify/merge Jinja2 dictionaries?如何修改/合并 Jinja2 字典?
【发布时间】:2011-02-11 18:42:54
【问题描述】:

我有一个 Jinja2 字典,我想要一个修改它的表达式 - 要么通过更改其内容,要么与另一个字典合并。

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

修改字典:失败。

>>> 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 '='

两阶段更新:打印多余的“无”。

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

那么如何通过更改属性或与另一个字典合并来修改 Jinja2 中的字典x

这个问题类似于:How can I merge two Python dictionaries as a single expression?——只要 Jinja2 和 Python 类似。

【问题讨论】:

    标签: merge dictionary jinja2


    【解决方案1】:

    我找到了另一个没有任何扩展的解决方案。

    {% set _dummy = x.update({4:5}) %}
    

    它使 x 更新。不要使用 _dummy。

    【讨论】:

      【解决方案2】:

      听起来像Jinja2 "do" statement extension 可能会有所帮助。启用此扩展将允许您重写:

      {{ 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}'
      >>> 
      

      【讨论】:

      • 另一个成语是{{ x.update({4:5})|default(x, true) }}
      【解决方案3】:

      我添加了一个过滤器来合并字典,即:

      >>> 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}'
      

      【讨论】:

        猜你喜欢
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 2016-01-13
        • 2016-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多