Django templates: Get current URL in another language

I think it is worth mentioning that there is a built-in function called translate_url.

from django.urls import translate_url
translate_url(url, lang_code)

I'm not using language prefixes, but translated urls instead. However, this template tag should also help you:

# This Python file uses the following encoding: utf-8

from django import template
from django.core.urlresolvers import reverse # from django.urls for Django >= 2.0
from django.core.urlresolvers import resolve # from django.urls for Django >= 2.0
from django.utils import translation

register = template.Library()

class TranslatedURL(template.Node):
    def __init__(self, language):
        self.language = language
    def render(self, context):
        view = resolve(context['request'].path)
        request_language = translation.get_language()
        translation.activate(self.language)
        url = reverse(view.url_name, args=view.args, kwargs=view.kwargs)
        translation.activate(request_language)
        return url

@register.tag(name='translate_url')
def do_translate_url(parser, token):
    language = token.split_contents()[1]
    return TranslatedURL(language)

It returns the current url in the desired language. Use it like this: {% translate_url de %}

Comments and suggestions for improvements are welcome.


This snippet should do it:

https://djangosnippets.org/snippets/2875/

Once you've added that as a custom template tag, then you can do something like:

<a href='{% change_lang 'fr' %}'>View this page in French</a>


A straightforward solution would be to use Django's translate_url function with a template tag:

# utils/templatetags/utils.py
from django.template import Library
from django.urls import translate_url as django_translate_url

register = Library()

@register.simple_tag(takes_context=True)
def translate_url(context, lang_code):
    path = context.get('request').get_full_path()
    return django_translate_url(path, lang_code)

Then use it this way in your html for language selection :

{% load i18n utils %}
{% get_available_languages as languages %}

<ul>
{% for lang_code, lang_name in languages %}
     <li><a href="{% translate_url lang_code %}">{{ lang_code }}</a></li>
{% endfor %}
</ul>

And for hreflangs :

{% get_available_languages as languages %}
{% for lang_code, lang_name in languages %}
    <link rel="alternate" hreflang="{{lang_code}}" href="{% translate_url lang_code %}" />
{% endfor %}

Hope this helps.