using url_for or uri_for inside jinja2 templates

2,391 views
Skip to first unread message

Hamish

unread,
Dec 13, 2011, 6:06:18 PM12/13/11
to webapp2
Hi,

I'm using webapp2 with jinja2. I'd like to be able to use the url_for
method within my templates. At present it says that url_for is an
unknown tag. Is there an easy way to make this work? I could pre-
calculate the urls in my python code and pass them to the template,
but I have a couple of places where I want to generate url's within
loops and so it would be a lot easier to have url_for available from
within the template itself.

File "templates/base.html", line 34, in template
{% url_for logout %}
TemplateSyntaxError: Encountered unknown tag 'url_for'.

thanks

Hamish

Fredrik Bonander

unread,
Dec 14, 2011, 4:29:19 AM12/14/11
to web...@googlegroups.com
You can add 'url_for' to you're webapp2-jinja2 config. Add it in the global section. ie:

webapp2_config = {}
webapp2_config['webapp2_extras.jinja2'] = {
    'template_path': 'templates',
    'compiled_path': None,
    'force_compiled': False,
    'environment_args': {
        'autoescape': True,
        'extensions': [
            'jinja2.ext.autoescape',
            'jinja2.ext.with_'
            ]
        },
    'globals': {
        'url_for' : webapp2.uri_for
    },
    'filters': None,
    }


This is the config you pass to webapp2 when the app is started up:
webapp2.WSGIApplication(config=config.webapp2_config)

..fredrik


Hamish Currie

unread,
Dec 14, 2011, 8:49:09 AM12/14/11
to web...@googlegroups.com
Hi Fredrik,

Thanks for your help - unfortunately I am still doing something wrong.

I've uploaded a small runnable project to github that demonstrates how I am setup.
https://github.com/hamish/webapp2_exmple/tree/master/src

When I run it with dev_appserver.py and navigate a browser to http://localhost:8080/ I get the following error output.

  File "templates/index.html", line 2, in template
    <a href="{% url_for debug %}">go Debug</a>

TemplateSyntaxError: Encountered unknown tag 'url_for'.

Is there something simple that I am missing?

thanks

Hamish

Gopal Patel

unread,
Dec 14, 2011, 9:43:54 AM12/14/11
to web...@googlegroups.com
url_for is a function. pass something to it.

url_for(end_point,someparameter=someparamenter) etc

Fredrik Bonander

unread,
Dec 14, 2011, 10:08:22 AM12/14/11
to web...@googlegroups.com
Haven't tried your github solution. You're jinja syntax is somewhat off, try this:

{{ url_for('debug') }}

..fredrik 

Hamish Currie

unread,
Dec 14, 2011, 9:02:16 PM12/14/11
to web...@googlegroups.com
That was the problem - thanks. I've updated the github repo so that anyone that comes across it dosen't make the same mistake that I made.

Hamish
Reply all
Reply to author
Forward
0 new messages