In a Django template, I need to transanlate some strings to a specific language (different from current one).
I would need something like this:
{% ta
This a modified version of Zalew's code which allows template's variable for the locale parameter:
from django.utils import translation
from django.template import Library, Node, Variable, TemplateSyntaxError
register = Library()
class TransNode(Node):
def __init__(self, value, lc):
self.value = Variable(value)
self.lc = Variable(lc)
def render(self, context):
translation.activate(self.lc.resolve(context))
val = translation.ugettext(self.value.resolve(context))
translation.deactivate()
return val
def trans_to(parser, token):
"""
force translation into a given language
usage : {% trans_to "string to translate" locale %}
"""
try:
tag_name, value, lc = token.split_contents()
except ValueError:
raise TemplateSyntaxError, '%r tag usage: {%% trans_to "string to translate" locale %%}' % token.contents.split()[0]
return TransNode(value, lc)
register.tag('trans_to', trans_to)