Reputation: 8055
If on most pages in the website I have a list of categories or recent articles that are loaded from the DB - how can I avoid duplicating code using flask and jinja2 ?
The way it is now, I have an html file which I include like :
{% include '/root/latest_articles.html' %}
And then every view has to pass the parameter (list of articles) to the template. I'd like to avoid this.
What's the best way to achieve this in Flask?
Thanks.
Edit
The "additional template context" would work .. I could export a function that loads the data from the DB and access it in the "latest_articles.html" template.
Is there another way ?
Upvotes: 2
Views: 2649
Reputation: 26050
You can add additional template context:
@app.context_processor
def additional_context():
return {
'content': get_page_content_context(request.endpoint, g.language),
'hot_links': get_hot_links(),
}
For templates code you can use macros or include.
UPD:
At first try use template inheritance and put your list of categories or recent articles in base template if your pages allow this.
You also can make template code just variable with `@app.context_processor', but I don't think that it's a good idea:
@app.context_processor
def additional_context():
return {
'recent_articles_markup': do_mark_safe(render_template(
'root/latest_articles.html', articles=get_recent_articles()),
}
Upvotes: 5
Reputation: 2631
My usual solution for such kind of stuff is Class inheritance with prepare function, please refer to my answer in other thread:
Different question, same solution. Dynamic navigation in Flask
Upvotes: 1