Creating links from page templates to translated content
You can get the user's preferred language through context/portal_languages/getPreferredLanguage. Use an object's 'getTranslation' method to get the translated object. You can then use this object's URL and title when linking to it.
Purpose
This document is about linking to translated content from a page template, for example a footer. You may want to do this on a website where several content items are linked from the footer, like a "Terms Of Service" or "Privacy Statement". These pages may be content items (instead of views), so content editors can modify them. For multilingual content, this presents the extra difficulty that if we are viewing the page in Gaelic, we also want the link to point to the Gaelic version of the content. So we try to create a link that points to the correct translation of the linked content.
Prerequisities
It's assumed that you are familiar with view templates and their customization, and that you have translatable content (LinguaPlone enabled) in your site.
Step by step
- From your template, fetch the translated object instead of linking to the "canonical" object. Here is a TAL snippet to pull in the translated object's URL and title:
<span tal:define=" link_object python: portal.get(content_id, None)" tal:condition="python: link_object is not None" > <a href="" tal:define=" preflang context/portal_languages/getPreferredLanguage; translated_object python: link_object.getTranslation(preflang) or link_object" tal:content="translated_object/title" tal:attributes="href translated_object/absolute_url"> [Title] </a> </span>It's assumed that you have the content that you want to link to available in the site root, with the id defined in
content_id. In case no content can be found by that id, we don't try to link to it. (Otherwise removing a linked content object might break your footer template, and your entire site.)
The same is true for the translation of the item: We have to check it's there, otherwise missing translations break the site. So in case there is no translation, we link to the untranslated object.