【问题标题】:Django: custom tag and tag evaluation in templateDjango:模板中的自定义标签和标签评估
【发布时间】: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


    【解决方案1】:

    你可以使用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 %}
    

    【讨论】:

    • 非常感谢您的帮助。我编辑了这个问题,因为你可以看到一个特定的案例不起作用。任何想法?再次感谢。
    • 哦,嵌套了!聪明的!再次感谢,双重接受的答案:)
    猜你喜欢
    • 2015-01-20
    • 2021-07-13
    • 2012-03-15
    • 2015-09-03
    • 1970-01-01
    • 2012-11-17
    • 2010-11-15
    • 1970-01-01
    相关资源
    最近更新 更多