James Huang
James Huang

Reputation: 876

Flask how to get variable in extended template

I've made a navbar in a flask app located in an html file that is extended to all other files. In the navbar, I have this code:

<ul class="navbar-nav">
    <li class="nav-item">
        <a class="nav-link active" aria-current="page" href="/">Home</a>
    </li>
    {% if 'user' in session %}
        <li class="nav-item">
            <a class="nav-link" href="/signup">Sign Up</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="/login">Login</a>
        </li>
    {% else %}
        <li class="nav-item">
            <a class="nav-link" href="/logout">Logout</a>
        </li>
    {% endif %}
</ul>

I have a dictionary element 'user' saved in a flask session that I want to be able to send to the base.html page. In other pages I use {% extends "base.html" %} to get the navbar, but if I want to pass the sessions variable through I'd have to send it through both the base.html file and the other file that extends it. Is there a way to get around this?

Upvotes: 2

Views: 980

Answers (2)

Iv&#225;n Guill&#233;n
Iv&#225;n Guill&#233;n

Reputation: 314

If someone is looking for the answer to the original request, here is an example using a variable in the base template that is defined in the partial template.

In your template base.html:

<html>
....
<a class="link{% if navbarActive == 'home' %} active {% endif %}">Home</a>
...

In your template:

{% set navbarActive = 'home' %}
{% extends "base.html" %}
... 

Hope it helps.

Upvotes: 2

Brady
Brady

Reputation: 419

What you are looking for is a context processor. Add this function in the same file where you have your @app.route('/') view function and all the variables you load into the template_config dictionary below will be available in any of your template .html files.

# Global HTML template variables.
@app.context_processor
def set_global_html_variable_values():
    if session.get('user'):
        user_in_session = True
    else:
        user_in_session = False
    template_config = {'user_in_session': user_in_session}
    return template_config





(base.html file)
{% if user_in_session %}
    <li class="nav-item">
        <a class="nav-link" href="/signup">Sign Up</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="/login">Login</a>
    </li>
{% else %}
    <li class="nav-item">
        <a class="nav-link" href="/logout">Logout</a>
    </li>
{% endif %}

Upvotes: 2

Related Questions