Django: Automatically fill information into template context

Sometimes you need a variable in your templates thats required for every page in your site.

Inserting it into every return statement in every view is a bit too troublesome.

Its much easier to add it into a "Context Processor". This will automatically insert the data you specify into every template rendered.

So in your app, create a file called "context_processor.py" and define the processors you need.

def custom_info(request):  
  return { 'MY_CUSTOM_INFO' : 'blah blah blah', }

Now in your settings, include the preprocessor.

TEMPLATE_CONTEXT_PROCESSORS = (  
  'django.core.context_processors.request',  
  'myapp.context_processors.custom_info',  
)

In your template, use it like normal without needing to load anything.

<div>Data: {{ MY_CUSTOM_INFO }}</div>
 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog