8eb519485d08d568a84e0982df7537e4f3a69c10
[prawokultury.git] / fnpdjango / templatetags / fnp_lang.py
1 from django.conf import settings
2 from django.core.urlresolvers import resolve, reverse
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         match = resolve(request.get_full_path())
36         view = match.url_name
37         if view is None:
38             view = match.func
39         if lang is None:
40             lang = translation.get_language()
41         with translation.override(lang):
42             url = reverse(view, args=match.args, kwargs=match.kwargs)
43     return url
44
45