2010-04-24 23 views
12

Tôi có một từ điển Jinja2 và tôi muốn một biểu thức đơn giản sửa đổi nó - hoặc bằng cách thay đổi nội dung của nó hoặc kết hợp với một từ điển khác.Làm cách nào để sửa đổi/hợp nhất từ ​​điển Jinja2?

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

Sửa đổi một dict: Không.

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

Cập nhật hai giai đoạn: In thừa "Không".

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

Sử dụng dict(x,**y): Không.

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

Vì vậy, làm thế nào để sửa đổi các từ điển x trong Jinja2 bằng cách thay đổi một thuộc tính hoặc sáp nhập với từ điển khác?

Câu hỏi này tương tự như: How can I merge two Python dictionaries as a single expression? - trong khi Jinja2 và Python tương tự nhau.

Trả lời

18

tôi tìm thấy một giải pháp mà không có phần mở rộng.

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

Nó làm cho x được cập nhật. Không sử dụng _dummy.

+2

Đây phải là câu trả lời được chấp nhận cho tôi ^^ –

+1

'dict.update()' trả về 'Không có' – smac89

2

tôi đã thêm một bộ lọc để kết hợp các từ điển, cụ thể là:

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

Âm thanh như Jinja2 "do" statement extension có thể giúp đỡ. Việc kích hoạt phần mở rộng này sẽ cho phép bạn ghi lại:

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

như

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

Ví dụ:

>>> 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}' 
>>> 
Các vấn đề liên quan