| 1 | |
| 2 | = CookBook - Template tags = |
| 3 | |
| 4 | == Easy translation == |
| 5 | |
| 6 | This creates a new tag pair, {{{{% translate %}}}} and {{{{% endtranslate %}}}} |
| 7 | which will translate every string between two backquotes. I made this |
| 8 | because I found the default i18n "trans" tag too bulky. |
| 9 | |
| 10 | {{{ |
| 11 | #!python |
| 12 | import re |
| 13 | from django.core import template |
| 14 | from django.utils import translation |
| 15 | |
| 16 | register = template.Library() |
| 17 | transl = re.compile("`(.*?)`") |
| 18 | |
| 19 | class TranslateNode(template.Node): |
| 20 | def __init__(self, nodelist): |
| 21 | self.nodelist = nodelist |
| 22 | |
| 23 | def render(self, context): |
| 24 | output = self.nodelist.render(context) |
| 25 | return transl.sub(lambda match: translation.gettext(match.group(1)), output) |
| 26 | |
| 27 | |
| 28 | def do_translate(parser, token): |
| 29 | nodelist = parser.parse(('endtranslate',)) |
| 30 | parser.delete_first_token() |
| 31 | return TranslateNode(nodelist) |
| 32 | |
| 33 | register.tag('translate', do_translate) |
| 34 | }}} |