简体   繁体   中英

Calling a route from a template

Can I have a route that renders a template that I can use in another template?

I imagine something like

@app.route('/tags/')
def tags():
    return render_template('tags.html', tags=create_tags())

and then somehow invoke the route from a different template.

<h2>Tags</h2>
{{ render('/tags/') }}

You can include the tags.html template in your template.

{% include "tags.html" %}

You have to pass the tags to your template, but this is the way to do it.

Routes don't render templates, functions do. All the route does is point a url to a function. So, the obvious solution to me is to have a function that returns the rendered tag template:

def render_tags_template():
    return render_template('tags.html', tags=create_tags())

Then we want to associate the function with the url "/tags"

app.add_url_rule('/tags', endpoint='tags', view_func=render_tags_template)

We also want to be able to access this function from within our templates. Accessing it via the url through another request would most likely be a job for ajax. So we have to get render_tags_template into the template context.

render_template('some_random_template.html', render_tags_template=render_tags_template

then in your some_random_template.html:

{{render_tags_template()}}

if you don't want to pass render_tags_template explicitly, you can add it as a template global:

app.jinja_env.globals['render_tags_template'] = render_tags_template

and use it freely in all of your templates, without having to pass it explicitly.

Depending on what your actually trying to do, simply including tags.html may be the best and easiest solution. Using a function to generate the content gives you a bit more control and flexibility.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM