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

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

提交回复
热议问题