Search code examples
djangodjango-templatesdjango-context

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:

  • some include statement that I can write directly in the templates to include context?
  • a way to get a context processor to do this?

Solution

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