Language-aware template inclusion

Looks up for a template based on the template-name plus the current users language code. Loads the template and renders it with the current context.

Example::

{% langinclude "foo/some_include.html" %}

Based on the users LANGUAGE_CODE, assumed we have 'de', it tries to render the template 'foo/some_include.html.de'. If that doesn't exists, it renders the template 'foo/some_include.html'. This is the default behavior of the include-Tag.

Basically this is a shortcut for the following code, just with a fallback for the default template::

fromdjango.templateimportLibrary,Nodefromdjango.templateimportTemplateSyntaxError,TemplateDoesNotExist,Variablefromdjango.template.loader_tagsimportIncludeNodefromdjango.template.loaderimportget_templatefromdjango.confimportsettingsregister=Library()classConstantLanguageIncludeNode(Node):def__init__(self,template_path):self.template_path=template_pathdefrender(self,context):try:t=get_template('%s.%s'%(self.template_path,context['LANGUAGE_CODE']))exceptTemplateDoesNotExist,KeyError:t=get_template(self.template_path)except:ifsettings.TEMPLATE_DEBUG:raisereturn''returnt.render(context)defdo_language_include(parser,token):""" Looks up for a template based on the template-name plus the current users language code. Loads the template and renders it with the current context. Example:: {% langinclude "foo/some_include.html" %} Based on the users LANGUAGE_CODE, assumed we have 'de', it tries to render the template 'foo/some_include.html.de'. If that doesn't exists, it renders the template 'foo/some_include.html'. This is the default behavior of the include-Tag. Basically this is a shortcut for the following code, just with a fallback for the default template:: {% ifequal LANGUAGE_CODE "de" %} {% include "foo/some_include.html.de" %} {% else %} {% include "foo/some_include.html" %} {% endifequal %} """bits=token.contents.split()iflen(bits)!=2:raiseTemplateSyntaxError,"%r tag takes one argument: the name of the template to be included"%bits[0]path=bits[1]ifpath[0]in('"',"'")andpath[-1]==path[0]:returnConstantLanguageIncludeNode(path[1:-1])returnIncludeNode(bits[1])register.tag('langinclude',do_language_include)

Justin, I was aware of this but a template name like "mytemplate_de.html" means, that you must use .html as the extension. Or it must replace the language before the last dot ... but what is, if there is no dot?

In most editors it is just one shortcut to set highlighting to html but feel free to extend it. ;)