Skip to content

Instantly share code, notes, and snippets.

@mammuth
Created July 24, 2019 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mammuth/38266a6e3bb8963224ace946f95ec838 to your computer and use it in GitHub Desktop.
Save mammuth/38266a6e3bb8963224ace946f95ec838 to your computer and use it in GitHub Desktop.
Template tag for django-cms which renders hreflang alternate meta-tags for CMS pages as well as app detail pages.
@register.inclusion_tag('templatetags/hreflangs.html', takes_context=True)
def render_hreflangs(context):
"""
This templatetag renders hreflang alternate tags for all available languages.
It supports CMS pages and detail pages of app hooks
The apps detail view needs to have `slug` as last part in the url, eg. /de/produkte-a-z/napura` (slug: napura`)
:param context:
:return:
"""
APP_NAMESPACES_WITH_SLUG_DETAIL_PAGES = ['brand', 'collection', 'news', 'jobs']
request = context.get('request')
alternate_languages = [l[0] for l in settings.LANGUAGES if l[0] != request.LANGUAGE_CODE]
context = {
'alternatives': []
}
for language in alternate_languages:
try:
app_namespace = request.current_page.application_namespace # eg. 'brand' or 'collection'
# Get alternative url for normal CMS page
if app_namespace is None:
url = request.current_page.get_absolute_url(language=language)
# Get alternative urls for apphook detail pages
elif app_namespace in APP_NAMESPACES_WITH_SLUG_DETAIL_PAGES:
view_name = resolve(request.path_info).url_name
slug = request.path_info.rstrip('/').split('/')[-1]
view_identifier = '{app}:{view}'.format(app=app_namespace, view=view_name)
with translation.override(language):
url = reverse(view_identifier, kwargs={'slug': slug})
# Page is a not-supported apphook
else:
continue
context.get('alternatives').append({
'language': language,
'url': url
})
except Exception as e:
logger.error('Error getting alternative languages of the page {}.\n{}'.format(
request.path_info,
traceback.format_stack(),
))
return context
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment