Passing variable urlname to url tag in django template

余生长醉 提交于 2019-11-27 13:45:03

问题


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!


回答1:


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.

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




回答2:


Note: this answer is only really relevant to versions of django before 1.3. If you are using django 1.3 or later, the required functionality is built-in - please see meshy's answer.

The built-in url tag cannot do this. However django-reversetag does exactly this (and more).

According to the readme, the reverse tag provided by this code provides:

  • Consistent syntax ("string literals" and variables)
  • Ability to reverse view names stored in context variables
  • Partial reversing



回答3:


for django 1.5 may be this is useful

usually, to access a variable passed from view we use {{variable}}

however, for url in template, the following does not work: {% url 'app:namespace' {{varible}} %}

simply use the following is fine: {% url 'app:namespace' varible %}




回答4:


if you are using Django 1.5 and up, django-reversetags is not required anymore for just passing view names as variables into templates, to be used within the url tag.

I was confused with the availability of django-reversetags, just thought of updating the matter correctly here.



来源:https://stackoverflow.com/questions/3057318/passing-variable-urlname-to-url-tag-in-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!