我编写了一个名为 addattrs
的自定义标记,它允许我轻松添加 HTML 属性。
我就是这样使用的:
<div>
<label>Last name</label>
{{ form.last_name|addattrs:"class=blue-form&placeholder=Please enter your name" }}
</div>
效果很好。但现在,我想将 value
属性添加到 HTML:
<div>
<label>Last name</label>
<!-- last_name is availaible from the current context -->
{{ form.last_name|addattrs:"class=blue-form&value=last_name" }}
</div>
问题是 last_name
没有按照我的表单进行评估和编写。如何强制评估last_name?我尝试了 {% with last_name as myvariable %}
block ,但结果完全相同。
谢谢。
编辑
alecxe 解决方案有效。 但是,如果该值是日期时间,则它不再起作用(没有 python 错误,但 HTML 中根本没有属性。)我尝试了以下方法:
{% with "class=blue-form&value="|add:birth_date as attrs %}
{{ form.birth_date|addattrs:attrs }}
{% endwith %}
最佳答案
您可以使用add
template filter :
{% with "class=blue-form&value="|add:last_name as attrs %}
{{ form.last_name|addattrs:attrs }}
{% endwith %}
<小时/>
对于日期值,需要先将其转换为字符串。在 View 中,或在模板中通过 date
template filter ,例如:
{% with birth_date|date:"D d M Y" as my_date %}
{% with "class=blue-form&value="|add:my_date as attrs %}
{{ form.last_name|addattrs:attrs }}
{% endwith %}
{% endwith %}
关于python - Django:模板中的自定义标签和标签评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27737917/