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

后端 未结 4 471
挽巷
挽巷 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:13

    From Django version 1.6, there is a language template tag so you can simply pass the desired language code:

    {% language "de" %}my block to translate{% endlanguage %}
    
    0 讨论(0)
  • 2021-01-01 01:20

    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)
    
    0 讨论(0)
  • 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 #}   
    <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 %}
    

    result:

    <p>test in deutsch</p>
    <p>test</p>
    <p>test in deutsch</p>
    <p>test</p>
    
    0 讨论(0)
  • 2021-01-01 01:24

    You could use the trans template tag inside your templates to translate strings to the desired language:

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

    You have to have USE_I18N set to True inside the settings.py file.

    Then you define LANGUAGE_CODE to control the default language for the whole site and add the LocaleMiddleware class to your MIDDLEWARE_CLASSES. Check out the How Django Discovers Language Preference section from the documentation.

    0 讨论(0)
提交回复
热议问题