Switch language in Django with the translated url redirect

后端 未结 2 1543
甜味超标
甜味超标 2020-12-18 11:09

I have internationalization correctly installed.

It\'s works with urls like:

/en/bookings/ #English
/es/reservas/ #Spanish

In the h

2条回答
  •  执念已碎
    2020-12-18 11:35

    When I had the same problem, I implemented a custom template tag (current_url) that, given the request in context, re-renders the url for the active language:

    {% load custom_tags %}
    
      {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} {# IMPORTANT! enclose the 'current_url' tag in a 'language' block #} {% language language.code %}
    • {{ language.name_local }}
    • {% endlanguage %} {% endfor %}

    Here is the code for the custom tag (custom_tags.py):

    import six
    import sys
    from django.template import Node, TemplateSyntaxError, Library
    from django.conf import settings
    
    register = Library()
    
    class CurrentURLNode(Node):
    
        def __init__(self, asvar=None):
            self.asvar = asvar
    
        def render(self, context):
            request = context['request']
            from django.core.urlresolvers import reverse, NoReverseMatch
            url = ''
            try:
                url = reverse(request.resolver_match.view_name, args=request.resolver_match.args, kwargs=request.resolver_match.kwargs, current_app=context.current_app)
            except NoReverseMatch:
                exc_info = sys.exc_info()
                if settings.SETTINGS_MODULE:
                    project_name = settings.SETTINGS_MODULE.split('.')[0]
                    try:
                        url = reverse(project_name + '.' + request.resolver_match.view_name,
                              args=request.resolver_match.args, kwargs=request.resolver_match.kwargs,
                              current_app=context.current_app)
                    except NoReverseMatch:
                        if self.asvar is None:                      
                            six.reraise(*exc_info)
                else:
                    if self.asvar is None:
                        raise
    
            if self.asvar:
                context[self.asvar] = url
                return ''
            else:
                return url
    
    @register.tag
    def current_url(parser, token):
        bits = token.split_contents()
        bits = bits[1:]
        asvar = None
        if len(bits) >= 2 and bits[-2] == 'as':
            asvar = bits[-1]
            bits = bits[:-2]
        if len(bits):
            raise TemplateSyntaxError("Unexpected arguments to current_url tag")
        return CurrentURLNode(asvar)
    

    There is no need to use the 'set_language' django view. There is no need to make a POST request to change the active language. With only html archors linking all your internationalized content together, it's better for SEO.

提交回复
热议问题