Python 从模板调用路由
我可以有一个路由来呈现我可以在另一个模板中使用的模板吗 我想象一下Python 从模板调用路由,python,flask,Python,Flask,我可以有一个路由来呈现我可以在另一个模板中使用的模板吗 我想象一下 @app.route('/tags/') def tags(): return render_template('tags.html', tags=create_tags()) 然后从另一个模板调用路由 <h2>Tags</h2> {{ render('/tags/') }} {% include "tags.html" %} 标签 {{render('/tags/')} 您可以在模板中包含
@app.route('/tags/')
def tags():
return render_template('tags.html', tags=create_tags())
然后从另一个模板调用路由
<h2>Tags</h2>
{{ render('/tags/') }}
{% include "tags.html" %}
标签
{{render('/tags/')}
您可以在模板中包含tags.html
模板
<h2>Tags</h2>
{{ render('/tags/') }}
{% include "tags.html" %}
您必须将
标记
传递给模板,但这是一种方法。路由不呈现模板,函数呈现模板。路由所做的只是将url指向一个函数。因此,对我来说,一个显而易见的解决方案是使用一个函数返回呈现的标记模板:
def render_tags_template():
return render_template('tags.html', tags=create_tags())
然后我们要将该函数与url“/标记”相关联
我们还希望能够从模板中访问此函数。通过另一个请求通过url访问它很可能是ajax的工作。因此,我们必须将render_tags_template放入模板上下文中
render_template('some_random_template.html', render_tags_template=render_tags_template
然后在您的some_random_template.html中:
{{render_tags_template()}}
如果不想显式传递render_tags_template,可以将其添加为全局模板:
app.jinja_env.globals['render_tags_template'] = render_tags_template
并在所有模板中自由使用它,而不必显式地传递它
根据您的实际尝试,简单地包含tags.html可能是最好、最简单的解决方案。使用一个函数来生成内容会给您带来更多的控制和灵活性。此外,如果您只想从模板中访问此函数,则无需添加url规则。如果希望用户转到/tags并查看单独呈现的tags.html,或者提供ajax api以使用javascript获取模板,那么可以添加url_规则。