Version 2 (modified by Nebojsa Djordjevic <nesh at studioquattro dot co dot yu>, 19 years ago) ( diff )

added blocktrans question

CookBook - Template tags

Easy translation

This creates a new tag pair, {% translate %} and {% endtranslate %} which will translate every string between two backquotes. I made this because I found the default i18n "trans" tag too bulky.

import re
from django.core import template
from django.utils import translation

register = template.Library()
transl = re.compile("`(.*?)`")

class TranslateNode(template.Node):
    def __init__(self, nodelist):
        self.nodelist = nodelist

    def render(self, context):
        output = self.nodelist.render(context)
        return transl.sub(lambda match: translation.gettext(match.group(1)), output)


def do_translate(parser, token):
    nodelist = parser.parse(('endtranslate',))
    parser.delete_first_token()
    return TranslateNode(nodelist)

register.tag('translate', do_translate)

Can you explain the difference between:

{% blocktrans %}
    asd adlkjfjalkdsfj lksajdfl sdkf jslakdfj
    asd adlkjfjalkdsfj lksajdfl sdkf jslakdfj
    asd adlkjfjalkdsfj lksajdfl sdkf jslakdfj
{% endblocktrans %}

and your method?

{% translate %}
    `saddasdasd asd ad asd`
    `saddasdasd asd ad asd`
{% endtranslate %}

Also, your tags are not picked up with make-messages so you must insert them manually into .po files.

Note: See TracWiki for help on using the wiki.
Back to Top