Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top