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

Pie*_*ert 5 django gettext django-templates internationalization

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

我需要这样的东西:

{% tans_to "de" "my string to translate" %}
or
{% blocktrans_to "de" %}my bloc to translate {% endblocktrans_to %}
Run Code Online (Sandbox Code Playgroud)

强制翻译成德语.

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

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

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

Har*_*mbe 14

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

{% language "de" %}my block to translate{% endlanguage %}
Run Code Online (Sandbox Code Playgroud)


zal*_*lew 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)
Run Code Online (Sandbox Code Playgroud)

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 %}
Run Code Online (Sandbox Code Playgroud)

结果:

<p>test in deutsch</p>
<p>test</p>
<p>test in deutsch</p>
<p>test</p>
Run Code Online (Sandbox Code Playgroud)