Search code examples
pythondjangodjango-templatesdjango-i18ndjango-template-filters

django i18n - get current path for different language


I am using Django and developing an i18n site serving many languages. I want to make a modal that stays in base.html, so that users can switch the language wherever they are.

I managed to do something like this.

<div class="modal-body">
{% get_available_languages as languages %}
    {% for lang_code, lang_name in languages %}
        {% language lang_code %}
        <a href="{% url 'home' %}" class="btn lang-btn {% ifequal request.LANGUAGE_CODE lang_code %}selected{% endifequal %}">{{lang_code|lang_name}}</a>
        {% endlanguage %}
    {% endfor %}
</div>

Which turns out urls like:/ja/, /en/, /fr/, etc.. but this kind of approach links to the main page only.

When using {{request.path}} or {{request.get_full_path}} for the url like:

<a href="{{ request.path }}" class="btn lang-btn {% ifequal request.LANGUAGE_CODE lang_code %}selected{% endifequal %}">{{lang_code|lang_name}}</a>

It doesn't include the i18n url patterns..

Is there any way for directing current url with request.path??

TARGET

When in /foo/ : /ja/foo/ /en/foo/ /fr/foo/

When in /bar/ : /ja/bar/ /en/bar/ /fr/bar/

Thanks in advance!


Solution

  • This topic is discussed in this SO question: Django templates: Get current URL in another language.

    In my project, I use this simple template tag (taken from https://djangosnippets.org/snippets/2875/), which returns the URL of the current view in another language.

    foo/templatetags/i18n_urls.py:

    from django import template
    from django.urls import translate_url
    
    register = template.Library()
    
    
    @register.simple_tag(takes_context=True)
    def change_lang(context, lang: str, *args, **kwargs):
        path = context['request'].path
    
        return translate_url(path, lang)
    

    some_template.html:

    {% load i18n_urls %}
    
    <ul>
        <li>
            <a href="{% change_lang 'en' %}">EN</a>
        </li>
        <li>
            <a href="{% change_lang 'cs' %}">CS</a>
        </li>
        <li>
            <a href="{% change_lang 'de' %}">DE</a>
        </li>
    </ul>
    

    Please note that translate_url function is not documented in the official Django docs. Here is the source code of this function: https://github.com/django/django/blob/master/django/urls/base.py#L161-L181.