5

I need to render my site without navbar if there is an argument in the request like nv=false and I want to pass a variable to context based on this so that the main template shows the block or not. my site also has lots of json-rpc functions, and I don't want to add extra overhead on it. how can I do this without rewriting all my views? (they are not class based and my site uses django 1.8)

Mohibeyki
  • 459
  • 6
  • 16
  • Possible duplicate of [How do I pass variables to all templates in django?](http://stackoverflow.com/questions/12030611/how-do-i-pass-variables-to-all-templates-in-django) – dsalaj Dec 09 '15 at 08:56
  • No, its not, needed to process request and then pass a variable, and context processor did it for me :) – Mohibeyki Dec 09 '15 at 09:19

1 Answers1

15

Just add context processor that will add this variable to context. Context processor is a simple python function

def navbar(request):
    return {'navbar_enabled': request.GET.get('nv', False)

and add it to the list of template context processors

TEMPLATE_CONTEXT_PROCESSORS = (
    ...
    'MODULE_NAME.navbar',
    ...
)
Nick
  • 1,134
  • 7
  • 12
  • 3
    If you are using the new `TEMPLATES` setting In Django 1.8+, set the `context_processors` option in the `TEMPLATES` setting, instead of `TEMPLATE_CONTEXT_PROCESSORS`. – Alasdair Nov 16 '15 at 13:55
  • I've got a filter on request that is now broken, my request is an empty string when this filter gets it! whats wrong? – Mohibeyki Nov 16 '15 at 14:21
  • 1
    I've got it, the request object is no longer passed to templates using the new SETTINGS object, I think it should have been pointed out on the docs somewhere https://docs.djangoproject.com/en/1.8/ref/settings/#std:setting-TEMPLATES – Mohibeyki Nov 16 '15 at 14:37
  • 1
    Others might be curious where a good place to put their custom context processors is. The pattern I've seen used in Two Scoops is just simply in `.context_processors`. – Taylor D. Edmiston Feb 14 '17 at 18:38