【问题标题】:Django: how to correctly pass an URL in include template tag?Django:如何在包含模板标签中正确传递 URL?
【发布时间】:2017-12-23 13:27:50
【问题描述】:

在两个不同的模板中,我有两个几乎相同的块,只是 url 不同:

template1.html

<div class="col-sm-4">
    <a href="{% url 'bo:article-list' %}" class="btn btn-block btn-secondary btn-sm"
       role="button">
        <i class="fa fa-chevron-left"></i> Annuler
    </a>
</div>

template2.html

<div class="col-sm-4">
    <a href="{{ article.get_absolute_url }}" class="btn btn-block btn-secondary btn-sm"
       role="button">
        <i class="fa fa-chevron-left"></i> Annuler
    </a>
</div>

我想把它弄干,创建一个模板,然后制作一个包含。 例如:

_cancel.html

<div class="col-sm-4">
<a href="{{ cancel_url }}" class="btn btn-block btn-secondary btn-sm"
   role="button">
    <i class="fa fa-chevron-left"></i> Annuler
</a>

对于 template2.html,它将适用于:

{% include 'includes/_cancel.html' with cancel_url=article.get_absolute_url %}

但是 template1.html 呢? 这显然行不通:

{% include 'includes/_cancel.html' with cancel_url={% url 'bo:article-list' %} 

我想有一个技巧。感谢您的帮助:)

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

    url 标记可用于通过使用as 将其结果保存到上下文变量中。

    {% url 'bo:article-list' as cancel_url %}
    

    您现在可以将其传递到您的包含标签中。

    【讨论】:

      猜你喜欢
      • 2021-02-15
      • 2021-09-10
      • 2017-08-11
      • 2013-06-05
      • 1970-01-01
      • 2021-08-29
      • 2017-05-29
      • 2014-08-06
      • 2019-07-31
      相关资源
      最近更新 更多