访问模板在 Django 中传递的变量
Access template passed variables in Django
我传给模板:
测试运行,即"get_list_or_404(TestRun)"
和
dict,就是这样的:
for testrun in testruns:
dict[testrun.id] = {
'passed' : bla bla,
'failed' : bla bla 2
}
实际上是 testrun.id
和来自 TestRun 模型
的一组信息之间的映射
在模板中我想这样做:
{% for testrun in testruns %}
console.log("{{ dict.testrun.id }}");
{% endfor %}
但不输出任何东西
console.log("{{ testrun.id }}");
将输出特定的 id(例如“37”)
console.log("{{ dict.37 }}");
会从字典中输出对应的值
那么,为什么这没有输出任何东西?
console.log("{{ dict.testrun.id }}");
我应该如何从 'passed'
和 'failed'
从 dict 获取数据:
另外,这个:
console.log("{{ dict[testrun.id] }}");
会输出这个错误:
TemplateSyntaxError at /path/dashboard
Could not parse the remainder: '[testrun.id]' from 'dict[testrun.id]'
点将被模板引擎视为属性查找的触发器,因此 dict.testrun.id
将被解析为 "try to find id
attribute from testrun
attribute from dict
"。相反,如果你想显示整个字典内容,你可能只是遍历字典:
{% for key, value in dict.items %}
Testcase: {{ key }}
Passed: {{ value.passed }}
Failed: {{ value.failed }}
{% endfor %}
或者,如果您要通过变量值查找字典,则必须制作自定义模板标签,就像这里描述的那样 - Django template how to look up a dictionary value with a variable
我传给模板:
测试运行,即"get_list_or_404(TestRun)"
和
dict,就是这样的:
for testrun in testruns:
dict[testrun.id] = {
'passed' : bla bla,
'failed' : bla bla 2
}
实际上是 testrun.id
和来自 TestRun 模型
在模板中我想这样做:
{% for testrun in testruns %}
console.log("{{ dict.testrun.id }}");
{% endfor %}
但不输出任何东西
console.log("{{ testrun.id }}");
将输出特定的 id(例如“37”)
console.log("{{ dict.37 }}");
会从字典中输出对应的值
那么,为什么这没有输出任何东西?
console.log("{{ dict.testrun.id }}");
我应该如何从 'passed'
和 'failed'
从 dict 获取数据:
另外,这个:
console.log("{{ dict[testrun.id] }}");
会输出这个错误:
TemplateSyntaxError at /path/dashboard
Could not parse the remainder: '[testrun.id]' from 'dict[testrun.id]'
点将被模板引擎视为属性查找的触发器,因此 dict.testrun.id
将被解析为 "try to find id
attribute from testrun
attribute from dict
"。相反,如果你想显示整个字典内容,你可能只是遍历字典:
{% for key, value in dict.items %}
Testcase: {{ key }}
Passed: {{ value.passed }}
Failed: {{ value.failed }}
{% endfor %}
或者,如果您要通过变量值查找字典,则必须制作自定义模板标签,就像这里描述的那样 - Django template how to look up a dictionary value with a variable