federico
federico

Reputation: 69

Django - retrieve data for extend template

I have a base template in my app, and a Profile template with the user data, with a bunch of other pages that they can navigate through. Every user has a market. I want to display the market name on every profile page, not bypassing every page a block tag.

base.html

<span class="title navbar-item">
    {% block market_name %}{% endblock %}
</span>

every-profile-page.html

{% block market_name %}{{market.name}}{% endblock market_name %}

Upvotes: 0

Views: 96

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477318

You can simply implement this as:

<span class="title navbar-item">
    {% block market_name %}{{ market.name }}{% endblock %}
</span>

or if you never will overwrite it, just omit the block:

<span class="title navbar-item">
    {{ market.name }}
</span>

As long as every view passes a market.name, this is not a problem.

It might however be cumbersome to pass a market to every context. You can make use of a context processor [Django-doc]. You can implement such context processor in any app, for example:

# app/context_processors.py

def market(request):
    return {
        'market': …
    }

then you register the context processor in the settings.py:

# settings.py

# …

TEMPLATES = [
    {
        # …
        'OPTIONS': {
            'context_processors': [
                # …
                'app.context_processors.market'
            ]
        }
        # …
    }
]

Upvotes: 1

Related Questions