Created
February 10, 2019 18:46
-
-
Save niespodd/29d11f6f6b2b96023d20f8eb95f15c47 to your computer and use it in GitHub Desktop.
dj i18n lang switcher template tag
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
register = Library() | |
@register.simple_tag(takes_context=True) | |
def change_lang(context, lang=None, *args, **kwargs): | |
try: | |
request = context.get('request') | |
path = request.path | |
url_parts = resolve(path) | |
if url_parts.url_name == 'model_i18n_slug_url': | |
# e.g. /catalog/<slug>/, where `slug` is a django-parler translatable-field | |
entry_obj = Entry.objects.distinct().get( | |
translations__slug=url_parts.kwargs["slug"] | |
) | |
entry_obj.set_current_language(lang) | |
url_parts.kwargs.update({'slug': entry_obj.slug}) | |
url = path | |
cur_language = get_language() | |
try: | |
activate(lang) | |
url = reverse(url_parts.view_name, kwargs=url_parts.kwargs) | |
finally: | |
activate(cur_language) | |
qs = request.GET.urlencode() | |
if len(qs) > 0: | |
url_s += "?{}".format(qs) | |
return url_s | |
except Exception: | |
return '' | |
# in templates | |
{% for lang_code, lang_name in LANGUAGES %} | |
<link rel="alternate" hreflang="{{ lang_code }}" href="{% change_lang lang_code %}"> <!-- mind this is relative! --> | |
{% endfor %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment