Django:模板中的自定义标签和标签评估

Django: custom tag and tag evaluation in template

我写了一个名为 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 %} 块,但结果完全一样。

谢谢。

编辑

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 %}

对于日期值,您需要先将其转换为字符串。在视图中,或通过 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 %}