如何在Django模板中指定URL? [英] How to specify URLs in Django templates?

查看:116
本文介绍了如何在Django模板中指定URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是:在Django模板中编写URL的正确方法是什么?

Question is: What's the right way of writing URL in Django templates?

如果我明确地编写它们(像这样):

If I write them explicitly (like this):

some_template.html

{% extends "base.html" %}
{% block someblock %}
    <a href="/some_url">Anchor</a>
{% endblock someblock %}

然后我决定更改我的URL方案必须同时更改模板和urls.py模块(这似乎与DRY原理冲突)

and then I decide to change my URL scheme I will have to change both - template and urls.py module (Seems this way conflicts with the DRY principles)

另一种方法是使用变量(像这样):

Another way is to use variables (like this):

some_template.html

{% extends "base.html" %}
{% block someblock %}
    <a href="{{ url_var }}">Anchor</a>
{% endblock someblock %}


views.py

def some_url (request):
    return HttpResponse('Hello, world!')

def another_url (request):
    return render_to_response('some_template.html', {'url_var': reverse('some_url')}

但是在这种情况下,如果我使用模板继承,则必须在上下文中指定所有url变量(也用于父模板)。

But in this case if I use template inheritance I have to specify in context ALL of the url variables (also for the parent templates). Probably it is not a good way too.

那是什么决定?

推荐答案

使用命名的URL {%url%} 标签。

Use named urls and the {% url %} tag.

urlpatterns = [
    #...
    url(r'^articles/$', views.archive, name='news-archive'),
    #...
]





{% url 'news-archive' %}

这篇关于如何在Django模板中指定URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆