[Pelican] Translate String According to Default Language in Theme


Pelican static site generator and i18n_subsites plugin can help you build website or blog which supports multiple languages. When generating websites for each supported language, some strings in the theme need to be translated according to default language while i18n_subsites plugin generates sub-site for each supported language. This post shows how to implement a gettext macro to achieve this goal.

Show by example. Assume three languages en, zh, and th are supported. Strings to be translated in the theme are Archives, Authors, and Categories.

Then put the following code, which includes strings to be translated and translation in the theme. (save as layout/includes/i18n.html in the theme directory in this case):

{% macro gettext(string, lang) -%}
  {%- if lang == 'en' -%}
    {{ string }}
  {%- elif lang == 'zh' -%}
    {%- if string == 'Archives' -%} 歸檔
    {%- elif string == 'Categories' -%} 分類
    {%- elif string == 'Authors' -%} 作者
    {%- else -%}
      {{ string }}
    {%- endif -%}
  {%- elif lang == 'th' -%}
    {%- if string == 'Archives' -%} สารบรรณ
    {%- elif string == 'Categories' -%} ประเภท
    {%- elif string == 'Authors' -%} ผู้เขียน
    {%- else -%}
      {{ string }}
    {%- endif -%}
  {%- else -%}
    {{ string }}
  {%- endif -%}
{%- endmacro %}

Next, in the layout, which is the template that every other template is inherited from (layout/layout.html in this case), import the above gettext macro in the beginning of the layout:

{%- from 'layout/includes/i18n.html' import gettext -%}

Finally, strings in the theme are translated like the following:

<span>{{ gettext('Archives', DEFAULT_LANG) }}</span>
<span>{{ gettext('Categories', DEFAULT_LANG) }}</span>
<span>{{ gettext('Authors', DEFAULT_LANG) }}</span>

For full working example, see [1].

For alternatives to localize theme, see [2] and [3].


Tested on: Ubuntu Linux 15.10, Python 2.7.10, Pelican 3.6.3.


References:

[1]GitHub - siongui/pelican-template
[2]Localizing themes with Jinja2 - i18n_subsites - pelican-plugins
[3][Pelican] Localize Theme via Jinja2 Custom Filter