Login

Get active page's url by another language (templatetag)

Author:
muratcorlu
Posted:
January 6, 2013
Language:
Python
Version:
1.4
Tags:
django i18n url
Score:
2 (after 3 ratings)

Usage:

{% load helper_tags %}

{% get_available_languages as languages %}

{% for lang_code, lang_name in languages %}
    <link rel="alternate" hreflang="{{ lang_code }}" href="{% change_lang lang_code %}">
{% endfor %}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from django.template import Library
from django.core.urlresolvers import resolve, reverse
from django.utils.translation import activate, get_language

register = Library()

@register.simple_tag(takes_context=True)
def change_lang(context, lang=None, *args, **kwargs):
    """
    Get active page's url by a specified language
    Usage: {% change_lang 'en' %}
    """

    path = context['request'].path
    url_parts = resolve( path )

    url = path
    cur_language = get_language()
    try:
        activate(lang)
        url = reverse( url_parts.view_name, kwargs=url_parts.kwargs )
    finally:
        activate(cur_language)


    return "%s" % url

More like this

  1. URL models by diverman 5 years, 5 months ago
  2. PostgreSQL fulltext with language translations by diverman 4 years, 7 months ago
  3. Language aware template loader by rmt 5 years, 11 months ago
  4. Language-aware template inclusion by bartTC 6 years, 1 month ago
  5. LocaleMiddleware without browser language discovery by ivellios 4 weeks, 1 day ago

Comments

elink (on June 21, 2013):

Nice Snippets, i used it for my website code reduc , and u have to say that its working great with translation French; English.

Thanks

#

Please login first before commenting.