I have a site where different projects/programs are listed, the list is dynamic so once a user clicks on a specific program e.g. /program/health the template should load one that has a "health" specific header (开发者_JAVA百科mast head). How can I load a base template based on the program selected?
Whenever you pass the path to a template to a function, you may substitute the hard-coded string for some variable of your choosing. If you do this it is extremele important to make sure it is a sensible value. To be fair, the template system will escape dangerous stuff and will not go outside the specified template dir, but trying to load a non-existing template will cause the view to crash and you don't want that.
If you have a model for the program, then get the model and use the slug as a template name, like this:
p = get_object_or_404(Program, slug = slug_from_url_or_whatever)
template = "program_%s.html" % p.slug
It is also possible to pass a list of templates to the loaders. If it doesn't find the first one, it will try the next one, etc. For example:
render_to_response([template, "default_program_template.html"], ...)
You could certainly use a custom Context Processor and some CSS to get the job done.
settings.py:
TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"yourproject.context_processors.header_context")
context_processors.py:
def header_context(request):
values = {'body_class': "default",}
if request.path == "/program/health/":
## Don't really use an if block, it's just nasty.
values['body_class'] = "health"
return values
views.py:
from django.shortcuts import render_to_response
from django.template import RequestContext
def view(request):
## Do magic stuff!
return render_to_response("template.html",
{},
context_instance=RequestContext(request))
template.html:
<body class="{{ body_class }}">
<!-- Whatever -->
</body>
Have you considered using a combination of CSS class names from a template variable and include template tags to accomplish this?
Something like:
<body class="{{ program }}">
<div>{% include program_specific_template %}</div>
<div>Common stuff...</div>
</body>
精彩评论