Django:如何强制翻译成模板中的给定语言?

时间:2010-07-04 21:07:47

标签: django django-templates internationalization gettext

在Django模板中,我需要将一些字符串转换为特定语言(与当前语言不同)。

我需要这样的东西:

{% tans_to "de" "my string to translate" %}
or
{% blocktrans_to "de" %}my bloc to translate {% endblocktrans_to %}

强制翻译成德语。

我知道我可以在视图中调用以下代码:

gettext.translation('django', 'locale', ['de'], fallback=True).ugettext("my string to translate")

我是否需要创建特定的模板标签?或者Django中是否已存在专用标签?

4 个答案:

答案 0 :(得分:13)

从Django版1.6开始,有一个language模板标记,因此您只需传递所需的语言代码即可:

{% language "de" %}my block to translate{% endlanguage %}

答案 1 :(得分:9)

templatetags / trans_to.py:

from django.utils import translation
from django.utils.translation import ugettext
from django.template import Library, Node,  Variable, TemplateSyntaxError
register = Library()

class TransNode(Node):
    def __init__(self, value, lc):
        self.value = Variable(value)
        self.lc = lc

    def render(self, context):        
        translation.activate(self.lc)
        val = ugettext(self.value.resolve(context))        
        translation.deactivate()        
        return val

def trans_to(parser, token):
    try:
        tag_name, value, lc = token.split_contents()
    except ValueError:
        raise TemplateSyntaxError, "%r tag requires arguments" % token.contents.split()[0]
    if not (lc[0] == lc[-1] and lc[0] in ('"', "'")):
        raise TemplateSyntaxError, "%r locale should be in quotes" % tag_name 
    return TransNode(value, lc[1:-1])

register.tag('trans_to', trans_to)

HTML:

{% load trans_to %}
{# pass string #}   
<p>{% trans_to "test" "de" %}</p>
<p>{% trans "test" %}</p>
{# pass variable #}
{% with "test" as a_variable %}
<p>{% trans_to a_variable "de" %}</p>
<p>{% trans a_variable %}</p>       
{% endwith %}

结果:

<p>test in deutsch</p>
<p>test</p>
<p>test in deutsch</p>
<p>test</p>

答案 2 :(得分:3)

这是Zalew代码的修改版本,它允许模板的变量用于locale参数:

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)

答案 3 :(得分:-3)

您可以使用模板中的trans模板标记将字符串翻译为所需的语言:

{% load i18n %}
{% trans "Hello" %}

您必须在USE_I18N文件中将True设置为settings.py

然后,您定义LANGUAGE_CODE来控制整个网站的默认语言,并将LocaleMiddleware课程添加到您的MIDDLEWARE_CLASSES。查看文档中的How Django Discovers Language Preference部分。