在 Django 模板中创建字典

tim*_*tim 2 django templates dictionary

所以,在 template.html 中我使用:

{% if dict %}
{{ s={} }}
{% endif %}
Run Code Online (Sandbox Code Playgroud)

错误是 -无法解析 's={}' 中的余数: '={}'。如何修复它?

Rob*_*ert 5

它仍然在谷歌搜索中排名第一,并且没有很好的解决方案。(在我看来)

我的解决方案:

自定义模板标签

from django import template
import ast

register = template.Library()

@register.simple_tag
def create_dict(str_dict):
    return ast.literal_eval(str_dict)
Run Code Online (Sandbox Code Playgroud)

然后在模板中

{% load yout_tag_file %}
{% create_dict "{ 'my_val_1': ['test', 'test', 'test'],'my_val_2': 2, }" as config %}
{% for key, value in config.items %}
   {{key}} - {{value}}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)