006faec1f2e7d93524d95b74838c7f676731e8a7
[fnpdjango.git] / fnpdjango / templatetags / fnp_lang.py
1 from django.conf import settings
2 from django.core.urlresolvers import resolve, reverse, Resolver404
3 from django import template
4 from django.utils import translation
5 from ..utils.views import get_current_object
6
7 register = template.Library()
8
9
10 @register.inclusion_tag('fnpdjango/lang_switcher.html', takes_context=True)
11 def lang_switcher(context):
12     """Context-aware language switcher.
13
14     Use ..utils.views.set_current_object to provide the context.
15     """
16     request = context['request']
17     obj = get_current_object(request)
18     languages = settings.LANGUAGES
19     if hasattr(obj, 'get_available_languages'):
20         available_languages = set(obj.get_available_languages())
21         languages = [lang for lang in languages if lang[0] in available_languages]
22     return {
23         'request': request,
24         'languages': languages,
25     }
26
27
28 @register.filter
29 def get_here_url(request, lang):
30     obj = get_current_object(request, for_url=True)
31     if hasattr(obj, 'get_absolute_url'):
32         with translation.override(lang):
33             url = obj.get_absolute_url()
34     else:
35         try:
36             match = resolve(request.get_full_path())
37         except Resolver404:
38             match = resolve('/')
39         view = match.url_name
40         if view is None:
41             view = match.func
42         if lang is None:
43             lang = translation.get_language()
44         with translation.override(lang):
45             url = reverse(view, args=match.args, kwargs=match.kwargs)
46     return url
47
48