How can I modify/merge Jinja2 dictionaries?

前端 未结 3 1579
慢半拍i
慢半拍i 2020-12-10 02:53

I have a Jinja2 dictionary and I want a single expression that modifies it - either by changing its content, or merging with another dictionary.

>>>         


        
相关标签:
3条回答
  • 2020-12-10 02:56

    Sounds like the Jinja2 "do" statement extension may help. Enabling this extension would allow you to rewrite:

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

    as

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

    Example:

    >>> 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}'
    >>> 
    
    0 讨论(0)
  • 2020-12-10 03:10

    I added a filter to merge dictionaries, namely:

    >>> 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}'
    
    0 讨论(0)
  • 2020-12-10 03:22

    I found another solution without any extension.

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

    It makes x updated. Don't use _dummy.

    0 讨论(0)
提交回复
热议问题