Reputation: 41
I have a template file temp1.html having code like this ---
{% load customtags %}
{% get_val 'VAR1' as var1 %} {% get_val 'VAR1' as var2 %}
In second template file temp2.html i want to use these variables var1
, var2
and var3
.
I am going to use these variables in multiple template files. So want to reuse the code every where.
I am including the temp1.html into temp2.html but these variables are not accessible into the temp2.html
{% include 'temp1.html' %}
So how to use these variables in another template files ?
Upvotes: 0
Views: 653
Reputation: 91
I don't know if it's possible to share values from the custom tags between various templates, so sorry if this doesn't answer exactlly to your specifications.
But when I needed to pass various variables to differents template I used a custom context_processor: You could define your contextual variable in a file like 'my_app.context_processors.py'
from django.conf import settings
from my_app.models import Authorization
def custom_contexts(request):
try:
user_level_projects = Authorization.get_user_level_projects(request.user)
except Exception:
user_level_projects = {}
# you can put here dynamics or constants data that will be accessible via the
# standard template syntaxes: ex -> {{ FILE_MAX_SIZE }}
return {
'APPLICATION_NAME': settings.APPLICATION_NAME,
'LOGO_PATH': settings.LOGO_PATH,
'APPLICATION_ABSTRACT': settings.APPLICATION_ABSTRACT,
'IMAGE_FORMAT': settings.IMAGE_FORMAT,
'FILE_MAX_SIZE': settings.FILE_MAX_SIZE,
'USER_LEVEL_PROJECTS': user_level_projects
}
then you have to add this new context_processor in your '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',
'my_app.context_processors.custom_contexts',
],
},
},
]
NB: In this example 'USER_LEVEL_PROJECTS' is actually a dictionary, but it could be anything else. I cannot find where in the doc I found this, but I'm sure you will find more infos.
Upvotes: 2