jinja2.ext.extract_from_ast¶
-
jinja2.ext.
extract_from_ast
(node, gettext_functions=('_', 'gettext', 'ngettext'), babel_style=True)[source]¶ Extract localizable strings from the given template node. Per default this function returns matches in babel style that means non string parameters as well as keyword arguments are returned as None. This allows Babel to figure out what you really meant if you are using gettext functions that allow keyword arguments for placeholder expansion. If you don’t want that behavior set the babel_style parameter to False which causes only strings to be returned and parameters are always stored in tuples. As a consequence invalid gettext calls (calls without a single string parameter or string parameters after non-string parameters) are skipped.
This example explains the behavior:
>>> from jinja2 import Environment >>> env = Environment() >>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}') >>> list(extract_from_ast(node)) [(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))] >>> list(extract_from_ast(node, babel_style=False)) [(1, '_', ('foo',)), (1, 'ngettext', ('foo', 'bar'))]
For every string found this function yields a
(lineno, function, message)
tuple, where:lineno
is the number of the line on which the string was found,function
is the name of thegettext
function used (if the string was extracted from embedded Python code), andmessage
is the string itself (aunicode
object, or a tuple ofunicode
objects for functions with multiple string arguments).
This extraction function operates on the AST and is because of that unable to extract any comments. For comment support you have to use the babel extraction interface or extract comments yourself.