0

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:

  • some include statement that I can write directly in the templates to include context?
  • a way to get a context processor to do this?
Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985

2 Answers2

2

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.

Melevir
  • 340
  • 3
  • 10
1

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

arie
  • 18,737
  • 5
  • 70
  • 76