0

Is it possible to pass an argument contains reverse name to the Django template URL tag

For example:

note: In this exampleconditional_URLis not a reverse name.

urls.py:

urlpatterns = patterns('views',
    url(r'^iframeViewURL/$', 'iframeView', name='iframeView'),
    url(r'^url_a/', 'view_a', name='view_a'),
    url(r'^url_b/', 'view_b', name='view_b'),
)

view.py:

def iframeView(**kwargs):
    kw = kwargs
    if kw['condition']:
        conditional_url = 'view_a'  # name of the URL pattern
    else:
        conditional_url = 'view_b'  # name of the URL pattern
    return render_to_response('iframe.html', {'conditional_URL': conditional_url},
                              context_instance=RequestContext(request, {}))

def view_a(*args):
    pass

def view_b(*args):
    pass

iframe.html:

<iframe src="{% url conditional_URL *args %}">
</iframe>

I try this but it's not working because of the conditional_URL is not a name of any url pattern.

Sencer H.
  • 1,201
  • 1
  • 13
  • 35

2 Answers2

2

It is possible since Django 1.3 if you add {% load url from future %} to your templatetag:

{% load url from future %}
<iframe src="{% url conditional_URL arg1 arg2 %}">
</iframe>

In Django 1.5 it is no longer necessary to add {% load url from future %}.

See the "Forwards compatibility" in the Django Documentation for the url templatetag for more information

Nicolas Cortot
  • 6,591
  • 34
  • 44
1

Instead of passing the name of url pattern to template, it will be easier to resolve and pass actual url to template.

Something like:

def iframeView(**kwargs):
    kw = kwargs
    if kw['condition']:
        conditional_url = 'name_a'  # name of the URL pattern
    else:
        conditional_url = 'name_b'  # name of the URL pattern

    return render_to_response('iframe.html', 
                          {'conditional_URL': reverse(conditional_url)},
                              context_instance=RequestContext(request, {}))

Then in template

<iframe src="{{conditional_URL}}"> </iframe>
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
Rohan
  • 52,392
  • 12
  • 90
  • 87