【发布时间】:2015-02-28 12:49:45
【问题描述】:
我编写了一个名为 addattrs 的自定义标签,它允许我轻松添加 HTML 属性。
我就是这样用的:
<div>
<label>Last name</label>
{{ form.last_name|addattrs:"class=blue-form&placeholder=Please enter your name" }}
</div>
效果很好。但是现在,我想在 HTML 中添加 value 属性:
<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 %} 块,但结果完全一样。
谢谢。
编辑
alecxe 解决方案有效。 但是,如果该值是日期时间,则它不再起作用(没有 python 错误,但 HTML 中根本没有属性。)我试过这个:
{% with "class=blue-form&value="|add:birth_date as attrs %}
{{ form.birth_date|addattrs:attrs }}
{% endwith %}
【问题讨论】:
标签: python django django-templates django-template-filters