pythondjangourltemplatestemplatetag

How to embed a tag within a url templatetag in a django template?


How do I embed a tag within a url templatetag in a django template?

Django 1.0 , Python 2.5.2

In views.py

def home_page_view(request):
    NUP={"HOMEPAGE": "named-url-pattern-string-for-my-home-page-view"}    
    variables = RequestContext(request, {'NUP':NUP})
    return render_to_response('home_page.html', variables)

In home_page.html, the following

NUP.HOMEPAGE = {{ NUP.HOMEPAGE }}

is displayed as

NUP.HOMEPAGE = named-url-pattern-string-for-my-home-page-view

and the following url named pattern works ( as expected ),

url template tag for NUP.HOMEPAGE = {% url named-url-pattern-string-for-my-home-page-view %}

and is displayed as

url template tag for NUP.HOMEPAGE = /myhomepage/

but when {{ NUP.HOMEPAGE }} is embedded within a {% url ... %} as follows

url template tag for NUP.HOMEPAGE = {% url {{ NUP.HOMEPAGE }} %}

this results in a template syntax error

TemplateSyntaxError at /myhomepage/
Could not parse the remainder: '}}' from '}}'
Request Method: GET
Request URL:    http://localhost:8000/myhomepage/
Exception Type: TemplateSyntaxError
Exception Value:    
Could not parse the remainder: '}}' from '}}'
Exception Location: C:\Python25\Lib\site-packages\django\template\__init__.py in __init__, line 529
Python Executable:  C:\Python25\python.exe
Python Version: 2.5.2

I was expecting {% url {{ NUP.HOMEPAGE }} %} to resolve to {% url named-url-pattern-string-for-my-home-page-view %} at runtime and be displayed as /myhomepage/.

Are embedded tags not supported in django?

is it possible to write a custom url template tag with embedded tags support to make this work?

{% url {{ NUP.HOMEPAGE }} %}


Solution

  • Maybe you could try passing the final URL to the template, instead?

    Something like this:

    from django.core.urlresolvers import reverse
    
    def home_page_view(request):
        NUP={"HOMEPAGE": reverse('named-url-pattern-string-for-my-home-page-view')}    
        variables = RequestContext(request, {'NUP':NUP})
        return render_to_response('home_page.html', variables)
    

    Then in the template, the NUP.HOMEPAGE should the the url itself.