如何在模板中使用webapp2.uri_for



webapp2说webapp2.uri_for是一个"可以传递给模板的独立uri_for版本"。听起来很完美。当我将它传递给Django模板渲染器时,如下所示:

import webapp2
from google.appengine.ext.webapp import template
self.response.out.write(template.render(path,
    { 'webapp2': webapp2 }))

并将其放入模板中

Please <a href="{{ webapp2.uri_for('contact') }}">send us 
your feedback</a>.

应用程序引擎1.7.0表示

TemplateSyntaxError:无法分析"webapp2.uri_for('contact')"中的剩余部分:"('contact'')"

如果我放

Please <a href="{{ webapp2 }}">send us your feedback</a>.

它显示

模块%20%27webapp2%27%20来自%20%27/usr/local/google_appengine/lib/webapp2/webapp2.pyc%27%

所以我知道webapp2正在进入模板。

我该如何让这个东西工作?

google.appengine.ext.webapp.template是一个django模板,但您的模板标记示例取自Jinja2。

有关webapp2+Jinja2的示例用法,请参阅本页:http://webapp-improved.appspot.com/api/webapp2_extras/jinja2.html

一旦您成功地呈现了一个简单的模板,就可以将'uri_for': webapp2.uri_for添加到上下文中,或者更好的是,将其添加到jinja2全局变量中。

因此,对于Django模板,作为一个原始示例,您可以创建一个简单的标签:

register = template.Library()
@register.simple_tag(name='uri_for')
def webapp2_uri_for(route_name):
    return webapp2.uri_for(route_name)

然后在你的模板中使用它,如下所示:

{% uri_for 'contact' %}

有关详细信息,请参阅:https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

最新更新