djangointernationalizationdjango-templates

Django templates: Get current URL in another language


I'm using i18n_patterns to create language prefixes in a Django app.

My URLs look like this:

/de/contact/
/fr/contact/
/it/contact/

In my base template, I'm looping over all available languages to show the language switch links.

{% get_available_languages as languages %}
<nav id="language_chooser">
    <ul>
        {% for lang_code, lang_name in languages %}
            {% language lang_code %}
            <li><a href="{% url 'home' %}" alt="{{ lang_name }}" title="{{ lang_name }}">{{ lang_code }}</a></li
            {% endlanguage %}
        {% endfor %}
    </ul>
</nav>

In this case, I'm reversing the "home" URL. Is there a way to get a translated URL of the current page instead?

If I'm on the German version of my "contact" page, I want the "fr" link to point to the French version of the "contact" page, not to the "home" page.


Solution

  • This solution should work for all URLs except when the arguments are language-dependent, as @Flash told us in the comments. I have simplified and updated the following code, so it will work with current Django versions >=3.

    from django import template
    from django.urls import resolve, reverse
    from django.utils import translation
    
    register = template.Library()
    
    @register.simple_tag(takes_context=True)
    def translate_url(context, language):
        view = resolve(context['request'].path)
        request_language = translation.get_language()
        translation.activate(language)
        url = reverse(view.url_name, args=view.args, kwargs=view.kwargs)
        translation.activate(request_language)
        return url
    

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

    Comments and suggestions for improvements are welcome.