django automatically pass context to specific templates only

I have context in a dict:

### settings.py. ###
CONTEXT = {'a':'b'}

And two templates that use that context t1.html and t2.html:

### t1.html ###
{{ a }}

### t2.html ###
{{ a }}

Both are meant to be included inside many other templates as:

### includer.html ###
{{ include 't1.html' }}

How can can I pass CONTEXT to t1.html and t2.html only:

  1. without polluting the context in any other template, including the includer.html templates
  2. automatically, that is, whenever t1.html and t2.html templates are used, I don't have to manually append settings.CONTEXT to the view's context as in:

    ### views.py ###
    import settings
    from django.shortcuts import render
    
    def view1(request):
        return render(
            request,
            'includer.html',
            dict( {'c':'d'}.items() + settings.CONTEXT.items())
        )
    

possible solutions:

Upvotes: 0

Views: 1235

Answers (2)

Melevir
Melevir

Reputation: 360

It's bad itea to do that, because it hides some of templates dependencies.

But using CBV you can create base view class and inherit from him when t1.html and t2.html are used. It's not automatic, but it makes extra context implicit.

Without CBV you should implicitly append settings.CONTEXT to current context as you do now.

Upvotes: 2

arie
arie

Reputation: 18972

Sounds like you want use an inclusion tag where you can set or import the desired context simply in your tag.

Upvotes: 1

Related Questions