如何将传递模型特定的 url 添加到模板。比方说,我想建立一个编辑链接。我猜想,使用 uri_for() 函数将是一种简单的方法。
但以下给了我“UndefinedError:'webapp2'未定义”
{% webapp2.uri_for("editGreeting", greeting.key().id()) %}
还是我应该在 MainPage-Request-Handler 中准备这些?如果是这样,我不知道如何将它们添加到每个问候语中。
以下代码示例取自: http ://webapp-improved.appspot.com/tutorials/gettingstarted/templates.html
控制器/处理程序
class MainPage(webapp2.RequestHandler):
def get(self):
guestbook_name=self.request.get('guestbook_name')
greetings_query = Greeting.all().ancestor(
guestbook_key(guestbook_name)).order('-date')
greetings = greetings_query.fetch(10)
if users.get_current_user():
url = users.create_logout_url(self.request.uri)
url_linktext = 'Logout'
else:
url = users.create_login_url(self.request.uri)
url_linktext = 'Login'
template_values = {
'greetings': greetings,
'url': url,
'url_linktext': url_linktext,
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
模板/视图:
<html>
<body>
{% for greeting in greetings %}
{% if greeting.author %}
<b>{{ greeting.author.nickname }}</b> wrote:
{% else %}
An anonymous person wrote:
{% endif %}
<blockquote>{{ greeting.content|escape }}</blockquote>
{% endfor %}
<form action="/sign" method="post">
<div><textarea name="content" rows="3" cols="60"></textarea></div>
<div><input type="submit" value="Sign Guestbook"></div>
</form>
<a href="{{ url }}">{{ url_linktext }}</a>
</body>
</html
BaseHandler 类是所有处理程序继承自的类。我按照@moraes 的建议尝试了以下操作。我仍然得到:
value = self.func(obj)
File "C:\Users\timme04\python\hellowebapp\handlers\basehandler.py", line 23, in jinja2
return jinja2.get_jinja2(factory=self.jinja2_factory)
File "C:\Users\timme04\python\hellowebapp\webapp2_extras\jinja2.py", line 212, in get_jinja2
jinja2 = app.registry[key] = factory(app)
TypeError: jinja2_factory() takes exactly 1 argument (2 given)
:(
import webapp2
from webapp2_extras import jinja2
class BaseHandler(webapp2.RequestHandler):
def jinja2_factory(app):
j = jinja2.Jinja2(app)
j.environment.filters.update({
# Set filters.
# ...
})
j.environment.globals.update({
# Set global variables.
'uri_for': webapp2.uri_for,
# ...
})
return j
@webapp2.cached_property
def jinja2(self):
# Returns a Jinja2 renderer cached in the app registry.
return jinja2.get_jinja2(factory=self.jinja2_factory)
def render_response(self, _template, **context):
# Renders a template and writes the result to the response.
rv = self.jinja2.render_template(_template, **context)
self.response.write(rv)