Skip to content

Instantly share code, notes, and snippets.

@lionel-panhaleux
Last active May 19, 2020 07:43
Show Gist options
  • Save lionel-panhaleux/0a690a67ce50aec301c3709d25759c67 to your computer and use it in GitHub Desktop.
Save lionel-panhaleux/0a690a67ce50aec301c3709d25759c67 to your computer and use it in GitHub Desktop.
Jinja template design for i18n

Simplest design

Maybe KISS, easy to code, a bit cumbersome to translate (4 separated translation strings will be generated)

<p>
    {% trans %}Combat occurs when a block succeeds,
    but can also be provoked directly using actions like{% endtrans %}
    <span class="card" onclick="dC('bumsrush')">{% trans %}Bum’s Rush{% endtrans %}</span>:
    {% trans %}Because of this card, other actions with similar effects
    are commonly called <strong>rush actions</strong>.
    It also gave its name to an entire archetype: the{% endtrans %}
    <a href="archetypes.html#rush">{% trans %}rush decks{% endtrans %}</a>.
</p>

Using variables

A bit verbose, but easier for translation (single translation block). The number of variables mat quickly become an issue.

<p>
    {% trans 
        card_bumsrush='<span class="card" onclick="dC(`bumsrush`)">'|safe
        endcard='</span>'|safe
        link='<a href="archetypes.html#rush">'|safe
        endlink='</a>'
    %}
    Combat occurs when a block succeeds,
    but can also be provoked directly using actions like
    {{ card_bumsrush }}Bum’s Rush{{ endcard }}:
    Because of this card, other actions with similar effects
    are commonly called <strong>rush actions</strong>.
    It also gave its name to an entire archetype:
    the {{ link }}rush decks{{ endlink }}.
    {% endtrans %}
</p>

Using variables and filters

Unsure this could work (untested code examples), but seems the most lean design to me if it does. This feels like it's less error-prone and, once setup, easier to use for everyone (page developers and translators). Maybe worth a try.

Template:

<p>
    {% trans 
        card_bumsrush='Bum’s Rush'|card|safe
        link_rush_decks=gettext('rush decks')|link('archetypes.html#rush')|safe
    %}
    Combat occurs when a block succeeds,
    but can also be provoked directly using actions
    like {{ card_bumsrush }}:
    Because of this card, other actions with similar effects
    are commonly called <strong>rush actions</strong>.
    It also gave its name to an entire archetype:
    the {{ link_rush_decks }}.
    {% endtrans %}
</p>

Backend:

import re
from unidecode import unidecode

def card(name):
    return re.sub(
        r"\s|'|\"|:|\(|\)",
        "",
        unidecode(name).lower(),
    )

environment.filters['card'] = card

def link(label, url):
    return f'<a href="{url}">{label}</a>'

environment.filters['link'] = link
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment