I have a settings module
settings
- base.py
- local.py
- prod.py
In the base.py
I am defining a variable called UMAMI_KEY
. I want to use the value of this variable in the base.html template.
How can I access this in the template?
I have a settings module
settings
- base.py
- local.py
- prod.py
In the base.py
I am defining a variable called UMAMI_KEY
. I want to use the value of this variable in the base.html template.
How can I access this in the template?
You can’t directly do that.
You either need to get that value in your view and pass it to the rendering engine in the context, or you need to create a custom context_processor that gets that value and adds it to the context. (see The Django template language: for Python programmers | Django documentation | Django)
The rendering engine only uses data available to it in the context when rendering a template.
Would it be possible with How to create custom template tags and filters | Django documentation | Django?
Yea, you could probably do it with a custom tag, too.
As a more general answer, yes, anything that lets you write code to extend the operation of the template engine would also work.
This would also mean that you could do it by extending or replacing the existing rendering engine and overriding the rendering method for a settings variable.
Thank you very much.
I used the context processor
approach since I want to use this value from the environment variable in all of my templates since it is in my base.html
project/context_processor.py
from django.conf import settings
def get_umami(request):
return {
'UMAMI_KEY': settings.UMAMI_KEY,
'UMAMI_ADDRESS': settings.UMAMI_ADDRESS
}
Added this to my TEMPLATES
context_processors
list:
curated.context_processors.get_umami',
Now I can access these values within the template without any problem.
{{ UMAMI_KEY }}
{{ UMAMI_ADDRESS }}