Version 3 (modified by g.brandl-nospam@…, 10 years ago) (diff)


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(, output)

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

register.tag('translate', do_translate)
Back to Top