将变量 urlname 传递给 django 模板中的 url 标签 [英] Passing variable urlname to url tag in django template

查看:37
本文介绍了将变量 urlname 传递给 django 模板中的 url 标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的(对于最近的更改widget" - 在这种情况下不是 django 小部件)是将 urlname 作为变量传递到我的模板中,然后像这样使用它: {% urlsitechangeobject.urlname %} 其中 urlname 是包含有效 url 名称的字符串.

What I'd like to do (for a recent changes 'widget' - not a django widget in this case) is pass a urlname into my template as a variable, then use it like so: {% url sitechangeobject.urlname %} Where urlname is a string containing a valid name for a url.

这可能吗?该模板不断说它找不到 sitechangeobject.urlname 作为名称(这是非常正确的,它不存在).有没有办法让它看起来在那个变量里面?

Is this possible? The template keeps breaking saying it can't find sitechangeobject.urlname as a name (which is quite right, it doesn't exist). Is there any way to make it look inside that variable?

如果没有,还有其他方法可以解决这个问题,只是想我会检查一下.

There are other ways to solve this problem if not, just thought I'd check though.

谢谢!

推荐答案

从 Django 1.3 开始,{% url %} 标签正确支持:

As of Django 1.3 the {% url %} tag properly supports:

{% url view_name_variable %}
{% url 'view_name_string' %}

...这成为 Django 1.5 中的默认行为.

...this becomes the default behaviour in Django 1.5.

以前,您只能选择这样做:

Previously, you had only the option to do this:

{% url view_name_string %}

要使标签在 Django 1.3 和 1.4 项目中以这种方式工作,您需要在使用它的每个模板的顶部添加以下行:

To get the tag to work in this way in Django 1.3 and 1.4 projects, you will need the following line to the top of every template you use it in:

{% load url from future %}

根据 Django 1.3 发布注释:

...在 Django 1.5 中,旧行为将被新行为取代.为确保与未来版本的 Django 兼容,应修改现有模板以使用新的未来库和语法.
...in Django 1.5, the old behavior will be replaced with the new behavior. To ensure compatibility with future versions of Django, existing templates should be modified to use the new future libraries and syntax.

请注意,对 {% load url from future %} 的支持已在 Django 1.9 中删除.

Note that support for {% load url from future %} has been removed in Django 1.9.

这篇关于将变量 urlname 传递给 django 模板中的 url 标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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