Reputation: 2150
I'm migrating from C#.NET to Python/Flask.
In .NET I have MasterPage, UserControl, PartialView
each has its own code behind.
e.g. I can save the check login functions in Login.ascx.cs
and render the Login.ascx
wherever I'd like to. If logged in, it shows the welcome message, else shows the login form.
But in Flask I only found {% include 'login.html' %}
which include the static html file.
How can I implement this design in Flask?
I May Have the Answer Now:
I'm not using g.user
and that's why I came here for help. Someone else suggested @app.context_processor
. I'm trying that and it seems like what I want. The similar global accessible design as g
.
Upvotes: 3
Views: 1479
Reputation: 159855
In spite of what its name might make you think it does include
does not insert the contents of static HTML files. It actually inserts the contents of rendered Jinja templates and it functions very much like a partial view from MVC (if I understand them correctly). It has access to the parent template context by default. So if, for example, you are storing the user on g.user
, since g
is accessible by default you can simply do this:
<-- login.html -->
{% if g.user.is_anonymous() %}
Login form goes here
{% else %}
Greetings {{g.user.full_name}}!
{% endif %}
And {% include "login.html" %}
wherever you want the login form / user greeting to show up.
Response to edit
If you want to make sure that user
is accessible to all templates you can indeed use context_processor
to add a user
:
@app.context_processor
def add_user():
# Get user
return {"user": user}
Upvotes: 2
Reputation: 6036
You should look into Flask-Login, which is an extension of Flask. After configuring it, you can achieve your requirements.
Upvotes: 0