Reputation: 91
I am new to flask and jinja templates. I know how to send data to template file but I want to know how to send data (not content) to layout template which is extended by template.
I have index.html, about.html and contact.html For these html files, I have common header and footer code in layout.html
{% extends "layout.html" %}
{% block title %}
SAMPLE TITLE
{% endblock %}
{% block body %}
SAMPLE BODY
{% endblock %}
And below is the image which shows my header
Here, Fashion and Jewellery are my categories and Ethnic Touch, Danglers, Hoops, etc are my sub-categories
And I want to populate these categories and sub-categories in layout.html (which is extended on every page) through for loop (python: multi-level dictionary).
In other html files, we can send data as below:
return render_template("result.html",result = result)
But in layout.html, which we are not rendering directly, how to pass data?
Please help.
Thanks in advance.
Upvotes: 0
Views: 1828
Reputation: 341
Passing it through your route as you normally would should work if it is defined or referenced inside each route, for example:
return render_template("index.html", menu=menu)
This will allow layout.html to render variables like {{ menu }} or {% for item in menu %} etc. (depending on how you are structuring your menu) even though index.html extends from it.
That being said, it may not be ideal to have to define or reference it and pass it in every single route (index, about, contact, or more if the site grows) so you could use a context processor before your routes:
@app.context_processor
def inject_menu():
# Fill in with your actual menu dictionary:
menu = {}
return dict(menu=menu)
This will let every route/view have access to that data. Here is information about context processors: https://flask.palletsprojects.com/en/1.1.x/templating/#context-processors
Upvotes: 2