Reputation: 145
I have written a custom context processor to return some frequently-used variables. I have followed multiple tutorials and read the official documentation, but nothing is happening: the context processor is either not loading or not returning any value. I am not getting any errors.
app name: auctions
context_processors.py
def test_context_processor(request):
return {
'message': 'Hello, world.'
}
settings.py
...
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media',
'auctions.context_processors.test_context_processor'
],
},
},
]
...
layout.html
...
<h1>{{ test_context_processor.message }}</h1>
...
When I inspect the H1 element, it is empty - nothing was returned. It looks like this:
<h1></h1>
I have tried:
{{ test_context_processor['message'] }}
(This generates an error)All I can think of is that every tutorial example is using the context processor to return a list of objects from a database, whereas I'm just returning a plain string value. But surely that can't matter, right? Thanks!
Upvotes: 1
Views: 732
Reputation: 18249
You were "nearly there" with this, in your template:
{{ test_context_processor['message'] }}
The only problem with this is that context processors just add data directly to the template context - which is essentially a dictionary holding your template variables. They don't scope or namespace it under anything, certainly not a name corresponding to the name of the context processor.
So you just need to do this:
{{ message }}
Upvotes: 4