我有这个:
{% for row in data: %}
<td
{{'value={{row['value']}}' if 'showit' in map and header in map['showit'] and 'value' in row}}
> ... </td>
{% endfor %}
但显然这不起作用。尝试使用 row
字典中的辅助列向单元格添加 HTML 属性。有什么想法吗?
最佳答案
假设您的问题在于获取 row['value']
的语法,请连接字符串而不是尝试嵌套 {{ }}
:
{{ 'value=' + row['value'] if True }}
当然将 True
替换为您的条件。如果需要引用参数:
{{ 'value="' + row['value'] + '"' 如果 True }}
正如@Reza-S4所建议的,您也可以将条件放在打印语句之外,这样会更清晰一点:
{% if 'showit' in map and header in map['showit'] and 'value' in row: %}
value="{{ row['value'] }}"
{% endif %}
关于 python jinja2 : using variable in template with conditional,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27473028/