简体   繁体   中英

Django: how to correctly pass an URL in include template tag?

In two different templates, I have two blocks almost identical, only the url is different:

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>

I'd like to make this dry, creating a template, and making an include then. For example:

_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>

For template2.html , it will work with:

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

But what about template1.html ? This obviously does NOT work :

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

I guess there is a trick. Thanks for your help :)

The url tag can be used to save its result to a context variable by using as .

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

and you can now pass this into your include tag.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM