I want have my url come from views.py and then I can pass it as variable to href
tag in template.
views.py:
context {
'urlLink': "{% url 'myapp:theURL' %}"
...
}
index.html:
<a href="{{ urlLink }}" LINK 1 </a>
I have the above and it is not working. I have also tried <a href="{{ urlLink|escape }}" LINK 1 </a>
but no success.
If you need to use something similar to the {% url %}
template tag in your view code, Django provides the django.core.urlresolvers.reverse()
. The reverse function has the following signature:
reverse(viewname, urlconf=None, args=None, kwargs=None)
So in your context:
context {
'urlLink': reverse('viewname')
}
Then you can use in your template:
<a href="{{urlLink}}">Link1</a>
you need reverse
context {
'urlLink': "%s" % reverse('view_name')
}
you cannot use {% url 'myapp:theURL' %}
in views.py since this is a template 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.