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

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

问题描述

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



这是可能吗?该模板不断打破说它找不到sitechangeobject.urlname作为一个名称(这是对的,它不存在)。有没有什么办法让它看起来变量?



还有其他方法来解决这个问题,如果没有,只是想我会检查。



谢谢!

解决方案

截至Django 1.3, %url%} 标签正确支持:

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

...这成为Django 1.5中的默认行为。 p>

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

  {% url view_name_string%} 

要在Django 1.3和1.4项目中使标签工作,您可以将需要以下行到您使用它的每个模板的顶部:

  {%从未来%加载url} 

根据Django 1.3发行说明

...在Django 1.5中,旧行为将被替换为新行为。为了确保与未来版本的Django兼容,现有的模板应该被修改为使用新的未来库和语法。


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.

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.

Thanks!

解决方案

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

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

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

Previously, you had only the option to do this:

{% url view_name_string %}

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 %}

According to the Django 1.3 release notes:

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

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

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