[英]Django: custom tag and tag evaluation in template
I wrote a custom tag named addattrs
that allow me add HTML attributes easily. 我编写了一个名为
addattrs
的自定义标签,该标签使我可以轻松添加HTML属性。
I uses it that way: 我用这种方式:
<div>
<label>Last name</label>
{{ form.last_name|addattrs:"class=blue-form&placeholder=Please enter your name" }}
</div>
It works well. 它运作良好。 But now, I'd like to add the
value
attribute to HTML: 但是现在,我想将
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>
The problem is last_name
is not evaluated and wrote as is in my form. 问题是未评估
last_name
并将其原样写在我的表单中。 How to force last_name to be evaluated? 如何强制对last_name进行求值? I tried a
{% with last_name as myvariable %}
block, but the result is exactly the same. 我尝试了
{% with last_name as myvariable %}
块,但结果完全一样。
Thanks. 谢谢。
EDIT 编辑
The alecxe solution works. alecxe解决方案有效。 However, if the value is a datetime, it does not work anymore (no python Error but no attribute at all in the HTML.) I tried this:
但是,如果值是日期时间,它将不再起作用(没有python错误,但HTML中完全没有属性。)我尝试了以下操作:
{% with "class=blue-form&value="|add:birth_date as attrs %}
{{ form.birth_date|addattrs:attrs }}
{% endwith %}
You can use add
template filter : 您可以使用
add
模板过滤器 :
{% with "class=blue-form&value="|add:last_name as attrs %}
{{ form.last_name|addattrs:attrs }}
{% endwith %}
For the date value, you need to convert it to a string first. 对于日期值,您需要先将其转换为字符串。 Either in the view, or in the template via
date
template filter , example: 在视图中,或者在通过
date
模板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 %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.