Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 872
Danilo Bargen Avatar asked Jul 11 '12 16:07

Danilo Bargen


3 Answers

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.

like image 82
Philipp Zedler Avatar answered Oct 18 '22 13:10

Philipp Zedler


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>

like image 41
seddonym Avatar answered Oct 18 '22 12:10

seddonym


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)
like image 8
Paweł Mucha Avatar answered Oct 18 '22 11:10

Paweł Mucha