[svn] implemented function to collect translations and documented it
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--HG-- branch : trunk
authored by Armin Ronacher · committed by Armin Ronacher · parent 3d4c5bb · Browse files · 5 files·+123 added−24 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+123 added−24 removed
- other:+123 added−24 removed
Provenance
- Commit
e9e1788- Tree
d655301- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
3d4c5bb
5 files changed+123 added−24 removed
modified:docs/src/contextenv.txt+8 added
31 unmodified lines32 33 If you don't provide a translator a default one is used to switch34 between singular and plural forms.35 36+ Have a look at the `i18n`_ section for more information.37+38+**def** `get_translations` *(self, name)*:39+40+ Get the translations for the template `name`. Only works if a loader41+ is present. See the `i18n`_ section for more details.42+43 **def** `apply_filters` *(self, value, context, filters)*:44 45 Now this function is a bit tricky and you usually don't have to override46 it. It's used to apply filters on a value. The Jinja expression91 unmodified lines138 139 Return `True` if `name` exists in the context.140 141 142+.. _i18n: i18n.txt143 .. _Quickstart: devintro.txt144 .. _gettext documentation: http://docs.python.org/lib/module-gettext.htmladded:docs/src/i18n.txt+72 added
1+====================2+Internationalization3+====================4+5+Jinja includes support for internationalized templates. Because usually the6+application includes i18n/l10n code too there is no script to collect7+translatable strings and no default translation interface. A simple8+implementation wouldn't fit into every application so there are a few things9+you have to do.10+11+12+Writing A Translator13+====================14+15+The most important thing is writing a translator and subclassing the16+Environment so that Jinja knows about the translator. Then you have to17+think of how to resolve the current language. You probably use Jinja in a18+multithreaded environment where each thread (request) might want to have19+a different language. The best way is putting the current language into20+the context, this can work automatically if you create a helper function21+for template rendering. But that's up to you.22+23+However. For many web applications this might be a way:24+25+.. sourcecode:: python26+27+ from jinja import Environment28+ from myapplication import get_translator29+30+ class ApplicationTranslator(object):31+32+ def __init__(self, language):33+ self.language = language34+ self.translator = get_translator(language)35+36+ def gettext(self, string):37+ return self.translator.ugettext(string)38+39+ def ngettext(self, singular, plural, n):40+ return self.translator.ungettext(singuarl, plural, n)41+42+43+ class ApplicationEnvironment(Environment):44+45+ def get_translator(self, context):46+ return ApplicationTranslator(context['LANGUAGE'])47+48+49+ env = ApplicationEnvironment()50+ tmpl = env.get_template('index.html')51+ tmpl.render(LANGUAGE='de_DE')52+53+54+Collecting Translations55+=======================56+57+The next step is to collect the translations. Every Jinja environment58+provides a function called `get_translations` which collects all59+translatable strings from an template.60+61+Example:62+63+.. sourcecode:: pycon64+65+ >>> env.get_translations('index.html')66+ [(1, u'foo', None), (2, u'Foo', None), (3, u'%d Foo', u'%d Foos')]67+68+The first item in the tuple is the linenumer, the second one is the69+singular form and the third is the plural form if given.70+71+Because Jinja is not bound to gettext you can now use these strings to72+create translation files for any translation system.modified:docs/src/index.txt+2 added-9 removed
24 unmodified lines25 - `Framework Integration <frameworks.txt>`_26 27 - `Debugging Support <debugging.txt>`_28 29+ - `Internationalization <i18n.txt>`_30+31 - Template Designer Documentation:32 33 - `Syntax Reference <designerdoc.txt>`_34 35 - `Differences To Django <fromdjango.txt>`_36 37 - `Recipies <recipies.txt>`_36-37-Undocumented So Far38--------------------39-40-- i18n for Developers41-42-- Writing Custom Loaders43-44-- Changelog / Authorsmodified:jinja/environment.py+9 added-1 removed
11 unmodified lines12 from jinja.lexer import Lexer13 from jinja.parser import Parser14 from jinja.loaders import LoaderWrapper15 from jinja.datastructure import Undefined, Context, Markup, FakeTranslator16-from jinja.utils import escape16+from jinja.utils import escape, collect_translations17 from jinja.exceptions import FilterNotFound, TestNotFound, SecurityException18 from jinja.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE19 20 90 unmodified lines111 that both of them have to return unicode!112 """113 return FakeTranslator()114 115+ def get_translations(self, name):116+ """117+ Load template `name` and return all translatable strings (note that118+ that it really just returns the strings form this template, not from119+ the parent or any included templates!)120+ """121+ return collect_translations(self.loader.parse(name))122+123 def apply_filters(self, value, context, filters):124 """125 Apply a list of filters on the variable.126 """87 unmodified linesmodified:jinja/utils.py+32 added-14 removed
13 unmodified lines14 import re15 import sys16 import string17 from types import MethodType, FunctionType18+from compiler.ast import CallFunc, Name, Const19 from jinja.nodes import Trans20 from jinja.datastructure import Markup21 22 try:84 unmodified lines107 words[i] = lead + middle + trail108 return u''.join(words)109 110 110-def find_translations(environment, source):111- """112- Find all translatable strings in a template and yield113- them as (lineno, singular, plural) tuples. If a plural114- section does not exist it will be None.115- """116- queue = [environment.parse(source)]117- while queue:118- node = queue.pop()119- if node.__class__ is Trans:120- yield node.lineno, node.singular, node.plural121- queue.extend(node.getChildNodes())122-123-111 def debug_context(env, context):112 """113 Use this function in templates to get a printed context.114 """102 unmodified lines217 return raise_template_exception(exc_value, filename,218 lineno, context)219 220 221+def collect_translations(ast):222+ """223+ Collect all translatable strings for the given ast.224+ """225+ todo = [ast]226+ result = []227+ while todo:228+ node = todo.pop()229+ if node.__class__ is Trans:230+ result.append((node.lineno, node.singular, node.plural))231+ elif node.__class__ is CallFunc and \232+ node.node.__class__ is Name and \233+ node.node.name == '_':234+ if len(node.args) in (1, 3):235+ args = []236+ for arg in node.args:237+ if not arg.__class__ is Const:238+ break239+ args.append(arg.value)240+ else:241+ if len(args) == 1:242+ singular = args[0]243+ plural = None244+ else:245+ singular, plural, _ = args246+ result.append((node.lineno, singular, plural))247+ todo.extend(node.getChildNodes())248+ result.sort(lambda a, b: cmp(a[0], b[0]))249+ return result250+251+252 class TracebackLoader(object):253 """254 Fake importer that just returns the source of a template.255 """142 unmodified lines