Skip to content
Myr

[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

5 files+123 added−24 removed

modified:docs/src/contextenv.txt+8 added
31 unmodified lines
3233 If you don't provide a translator a default one is used to switch34 between singular and plural forms.3536 Have a look at the `i18n`_ section for more information.3738**def** `get_translations` *(self, name)*:3940 Get the translations for the template `name`. Only works if a loader41 is present. See the `i18n`_ section for more details.4243**def** `apply_filters` *(self, value, context, filters)*:4445 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 expression
91 unmodified lines
138139 Return `True` if `name` exists in the context.140141142.. _i18n: i18n.txt143.. _Quickstart: devintro.txt144.. _gettext documentation: http://docs.python.org/lib/module-gettext.html
added:docs/src/i18n.txt+72 added
1====================2Internationalization3====================45Jinja includes support for internationalized templates. Because usually the6application includes i18n/l10n code too there is no script to collect7translatable strings and no default translation interface. A simple8implementation wouldn't fit into every application so there are a few things9you have to do.101112Writing A Translator13====================1415The most important thing is writing a translator and subclassing the16Environment so that Jinja knows about the translator. Then you have to17think of how to resolve the current language. You probably use Jinja in a18multithreaded environment where each thread (request) might want to have19a different language. The best way is putting the current language into20the context, this can work automatically if you create a helper function21for template rendering. But that's up to you.2223However. For many web applications this might be a way:2425.. sourcecode:: python2627 from jinja import Environment28 from myapplication import get_translator2930 class ApplicationTranslator(object):3132 def __init__(self, language):33 self.language = language34 self.translator = get_translator(language)3536 def gettext(self, string):37 return self.translator.ugettext(string)3839 def ngettext(self, singular, plural, n):40 return self.translator.ungettext(singuarl, plural, n)414243 class ApplicationEnvironment(Environment):4445 def get_translator(self, context):46 return ApplicationTranslator(context['LANGUAGE'])474849 env = ApplicationEnvironment()50 tmpl = env.get_template('index.html')51 tmpl.render(LANGUAGE='de_DE')525354Collecting Translations55=======================5657The next step is to collect the translations. Every Jinja environment58provides a function called `get_translations` which collects all59translatable strings from an template.6061Example:6263.. sourcecode:: pycon6465 >>> env.get_translations('index.html')66 [(1, u'foo', None), (2, u'Foo', None), (3, u'%d Foo', u'%d Foos')]6768The first item in the tuple is the linenumer, the second one is the69singular form and the third is the plural form if given.7071Because Jinja is not bound to gettext you can now use these strings to72create translation files for any translation system.
modified:docs/src/index.txt+2 added-9 removed
24 unmodified lines
25 - `Framework Integration <frameworks.txt>`_2627 - `Debugging Support <debugging.txt>`_2829 - `Internationalization <i18n.txt>`_3031- Template Designer Documentation:3233 - `Syntax Reference <designerdoc.txt>`_3435 - `Differences To Django <fromdjango.txt>`_3637 - `Recipies <recipies.txt>`_3637Undocumented So Far38-------------------3940- i18n for Developers4142- Writing Custom Loaders4344- Changelog / Authors
modified:jinja/environment.py+9 added-1 removed
11 unmodified lines
12from jinja.lexer import Lexer13from jinja.parser import Parser14from jinja.loaders import LoaderWrapper15from jinja.datastructure import Undefined, Context, Markup, FakeTranslator16from jinja.utils import escape16from jinja.utils import escape, collect_translations17from jinja.exceptions import FilterNotFound, TestNotFound, SecurityException18from jinja.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE1920
90 unmodified lines
111 that both of them have to return unicode!112 """113 return FakeTranslator()114115 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))122123 def apply_filters(self, value, context, filters):124 """125 Apply a list of filters on the variable.126 """
87 unmodified lines
modified:jinja/utils.py+32 added-14 removed
13 unmodified lines
14import re15import sys16import string17from types import MethodType, FunctionType18from compiler.ast import CallFunc, Name, Const19from jinja.nodes import Trans20from jinja.datastructure import Markup2122try:
84 unmodified lines
107 words[i] = lead + middle + trail108 return u''.join(words)109110110def 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())122123111def debug_context(env, context):112 """113 Use this function in templates to get a printed context.114 """
102 unmodified lines
217 return raise_template_exception(exc_value, filename,218 lineno, context)219220221def 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 result250251252class TracebackLoader(object):253 """254 Fake importer that just returns the source of a template.255 """
142 unmodified lines