M
M
Michael2021-04-02 15:28:03
Flask
Michael, 2021-04-02 15:28:03

Flask jinja2 extends how to pass data to base template?

Hello. The situation is the following.
There is a base template that defines a header. There are notifications in this header, this is a dynamic list that should display information about new user notifications.
Since the header is the same for all pages, it was logical to use it as a base template, and extend it to the necessary pages.
The problem is that this template is not called anywhere, therefore I cannot pass data from the database to it, since the template engine must receive data explicitly when render_template.

The question is, how can I render the header in advance by passing data there? Or do I need to transfer data to render_template for each page, this is clearly not the correct implementation.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Michael, 2021-04-04
@moonz

The answer was found on ru.stackoverflow

from flask import Blueprint

from utils import db_connect

app = Blueprint("name", __name__, template_folder='templates')

@app.route("/")
def index():
  return render_template("index.html")

@app.context_processor
def any_data_processor():
  with db_connect.connect() as con: 
# тут же могла быть работа с кешем/API/файловой системой и др.
    ....
  result = ...
  return dict(any_data=result)

After that, you can access inside all templates without explicitly passing the context there.
{{any_data}}

I
iddqda, 2021-04-02
@iddqda

probably something like this is possible:
https://realpython.com/primer-on-jinja-templating/...
you can also reserve a block in the header and shove the data there using JS

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question