我正在尝试使用像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)以及创建app的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')])发布于 2017-04-20 08:32:49
我找到了另一种方法来做这个。问题在于我呈现模板的方式。
首先,我需要添加这一行并删除MakoTemplates,从而在main.py文件中创建LOOKUP实例。
MakoTemplates(app)然后,我不再使用LOOKUP.get_template...,而是返回:
return render_template(templates[chosen]['template'], templates=templates)这让我可以删除这些标签。
发布于 2017-04-20 08:15:53
导入是无法避免的,<%! %>被称为模块级块,当模板加载到内存中时,它将被执行一次。但是它不能在模板之间共享。正如Python模块的工作方式一样,在使用之前,需要明确地导入所有内容。
https://stackoverflow.com/questions/43512956
复制相似问题