Django: How to force translation into a given language inside a template?

后端 未结 4 495
挽巷
挽巷 2021-01-01 00:24

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         


        
4条回答
  •  臣服心动
    2021-01-01 01:21

    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 #}   
    

    {% trans_to "test" "de" %}

    {% trans "test" %}

    {# pass variable #} {% with "test" as a_variable %}

    {% trans_to a_variable "de" %}

    {% trans a_variable %}

    {% endwith %}

    result:

    test in deutsch

    test

    test in deutsch

    test

提交回复
热议问题