【发布时间】:2017-09-16 16:48:03
【问题描述】:
我正在尝试使用url_for 等方法创建一个从另一个模板继承的模板。如果我删除 import 语句,我会收到错误:
TypeError
TypeError: 'Undefined' object is not callable
我可以去掉下面的导入吗?
main.html 文件:
<!doctype html>
<%!
from flask.helpers import url_for
from flask.globals import request
%>
<html lang=en>
<head>
<%block name="additional_scripts"/>
</head>
<body>
</body>
<h1>Presence analyzer</h1>
<ul>
% for key, template in templates.items():
<li
% if request.path == '/statistics/{}/'.format(template['name']):
id="selected"
% endif
>
<a href="${url_for('statistics_view', chosen=template['name'])}">${template['description']}</a>
</li>
% endfor
</ul>
</html>
继承文件:
<%inherit file="main.html"/>
<%!
from flask.helpers import url_for
%>
<%block name="additional_scripts">
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart", "timeline"], 'language': 'pl'});
</script>
<script src="${url_for('static', filename='js/presence_weekday.js')}"></script>
</%block>
调用视图方法:
@app.route('/statistics/<chosen>/')
def statistics_view(chosen):
try:
return LOOKUP.get_template(templates[chosen]['template']).render(templates=templates)
except KeyError:
abort(404)
还有main.py 创建应用的文件:
import os
from flask import Flask
from mako.lookup import TemplateLookup
app = Flask(__name__) # pylint: disable=invalid-name
LOOKUP = TemplateLookup(directories=[os.path.join(os.path.dirname(os.path.realpath(__file__)),
'templates')])
【问题讨论】: