python - Template include tag: Choose another template if it does not exist -
i include different template depending request. example:
suppose request has:
request.country = 'spain' request.city = 'madrid'
i want include "index.html" view but:
---- if myapp/index_madrid.html exist
{% include "myapp/index_madrid.html" %}
---- elif myapp/index_spain.html exist
{% include "myapp/index_spain.html" %}
---- else go default version
{% include "myapp/index.html" %}
how can achieve behaviour in transparent way? mean, like:
{% my_tag_include "myapp/index.html" %} {% my_tag_include "myapp/another_view.html" p='xxx' only%} {% my_tag_include "myapp/any_view.html" p='sss' a='juan' %}
and achieve cascading loading explained before.
thanks
one possibility implement kind of logic in view:
# views.py django.template.loader import select_template class myview(view): def get(self, request): include_template = select_template([ 'myapp/index_{}.html'.format(request.city), 'myapp/index_{}.html'.format(request.country), 'myapp/index.html' ]) ctx = { 'include_template': include_template } return render(request, 'myapp/base.html', ctx) # myapp/base.html {% include include_template %}
select_template() return first template in passed list exists. include
tag supports including compiled templates beginning django 1.7
, should work fine if on 1.7 or above.
update: reuse across multiple views
# utils.py django.template.loader import select_template def get_approriate_template(tokens, app_name): templates = ['{}/index_{}.html'.format(app_name, x) x in tokens] templates.append('{}/index.html'.format(app_name)) return select_template(templates) # views.py .utils import get_approriate_template class myview(view): def get(self, request): tokens = [request.city, request.country] ctx = { 'include_template': get_appropriate_template(tokens, app_name='myapp') } return render(request, 'myapp/base.html', ctx)
update: rendering template template tag
# templatetags/myapp_extras.py django import template register = template.library() @register.simple_tag(takes_context=true) def my_tag_include(context): django.template.loader import select_template include_template = select_template([ 'myapp/index_{}.html'.format(context['request'].city), 'myapp/index_{}.html'.format(context['request'].country), 'myapp/index.html' ]) return include_template.render(context) # myapp/base.html {% load myapp_extras %} {% my_tag_include %}
Comments
Post a Comment