我想在Django模板中设置一些来自dict的变量。我访问dict项和值,但当我尝试从中设置一些值时,它不起作用
这是可行的:
{% for key, value in v.items %}
{% if key == 'title' %}<tr>{{ value }}</tr>{% endif%}
{% if key == 'name' %}<tr>{{ value }}</tr>{% endif%}
{% endfor %}
这不起作用:
{% for key, value in v.items %}
{% if key == 'title' %}{% with title as value %}{%$ endwith %}{%
endif%}
{% if key == 'name' %}{% with name as value %}{%$ endwith %}{%
endif%}
{% endfor%}
<tr>{{ title }}</tr><tr>{{ name }}</tr>
我想从dict值在django模板中设置一个VAR!
发布于 2019-03-23 17:38:28
with
用于定义本地上下文,而不是“设置变量”。因此,正如Pankaj所说,除非变量在{% with ... %}{% endwith %}
中,否则它们不会工作
请注意,它应该是with existing_var as new_var_name
,而不是反过来。您也不需要使用$
来结束标记。
因此,这将打印出变量(不完全是您想要的,但它们会显示出来):
{% for key, value in v.items %}
{% if key == 'title' %}{% with value as title %}{{ title }}{% endwith %}{%
endif%}
{% if key == 'name' %}{% with value as name %}{{ name }}{% endwith %}{%
endif%}
{% endfor%}
但是,您不需要这样做(而且只更改变量的名称是没有意义的)。如果v
是一个字典,为什么不这样做:
<tr>{{ v.title }}</tr><tr>{{ v.name }}</tr>
通常,您不应该真的尝试在Django模板中设置变量。如果您需要提取数据/执行转换,您可能应该在视图中执行此操作,或者使用模板标记。
发布于 2019-03-23 18:28:24
@geekfish提供的解决方案:
{% for key, value in v.items %}
<tr>{{ v.title }}</tr><tr>{{ v.name }}</tr>
{% endfor%}
;)
https://stackoverflow.com/questions/55316314
复制