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

 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. Class Feeds DRY TemplateTag by gmandx 3 years ago
  2. Improved many-page pagination by dokterbob 2 years, 8 months ago
  3. Page numbers with ... like in Digg by Ciantic 4 years, 1 month ago
  4. Active class for navigation link by cschand 3 years, 8 months ago
  5. Absolute URL Templatetag by johnboxall 3 years, 12 months ago

Comments

(Forgotten your password?)