Skip to content
Myr

Add support for `{% trans trimmed ... %}`

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Same behavior as in Django: All linebreaks and the whitespace surrounding linebreaks are replaced with a single space. closes #504

authored by Adrian Moennich · committed by Adrian · parent c7dfa21 · Browse files · 7 files+123 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+123 added−1 removed

  • tests:+68 added−0 removed
  • other:+55 added−1 removed

7 files+123 added−1 removed

modified:docs/api.rst+7 added
609 unmodified lines
610``json.dumps_kwargs``:611 Keyword arguments to be passed to the dump function. The default is612 ``{'sort_keys': True}``.613614.. _ext-i18n-trimmed:615616``ext.i18n.trimmed``:617 If this is set to `True`, ``{% trans %}`` blocks of the618 :ref:`i18n-extension` will always unify linebreaks and surrounding619 whitespace as if the `trimmed` modifier was used.620621622Utilities623---------624625These helper functions and classes are useful if you add custom filters or
307 unmodified lines
modified:docs/extensions.rst+9 added
109 unmodified lines
110.. _Babel: http://babel.pocoo.org/111112.. _newstyle-gettext:113114Whitespace Trimming115~~~~~~~~~~~~~~~~~~~116117.. versionadded:: 2.10118119Linebreaks and surrounding whitespace can be automatically trimmed by enabling120the ``ext.i18n.trimmed`` :ref:`policy <ext-i18n-trimmed>`.121122123Newstyle Gettext124~~~~~~~~~~~~~~~~125126.. versionadded:: 2.5
224 unmodified lines
modified:docs/templates.rst+16 added
1490 unmodified lines
14911492 {% trans ..., user_count=users|length %}...1493 {% pluralize user_count %}...{% endtrans %}14941495When translating longer blocks of text, whitespace and linebreaks result in1496rather ugly and error-prone translation strings. To avoid this, a trans block1497can be marked as trimmed which will replace all linebreaks and the whitespace1498surrounding them with a single space and remove leading/trailing whitespace::14991500 {% trans trimmed book_title=book.title %}1501 This is {{ book_title }}.1502 You should read it!1503 {% endtrans %}15041505If trimming is enabled globally, the `notrimmed` modifier can be used to1506disable it for a `trans` block.15071508.. versionadded:: 2.101509 The `trimmed` and `notrimmed` modifiers have been added.15101511It's also possible to translate strings in expressions. For that purpose,1512three functions exist:15131514- `gettext`: translate a single string
142 unmodified lines
modified:jinja2/defaults.py+1 added
46 unmodified lines
47 'urlize.target': None,48 'truncate.leeway': 5,49 'json.dumps_function': None,50 'json.dumps_kwargs': {'sort_keys': True},51 'ext.i18n.trimmed': False,52}535455# export all constants
1 unmodified line
modified:jinja2/ext.py+19 added-1 removed
8 unmodified lines
910 :copyright: (c) 2017 by the Jinja Team.11 :license: BSD.12"""13import re1415from jinja2 import nodes16from jinja2.defaults import BLOCK_START_STRING, \17 BLOCK_END_STRING, VARIABLE_START_STRING, VARIABLE_END_STRING, \18 COMMENT_START_STRING, COMMENT_END_STRING, LINE_STATEMENT_PREFIX, \
205 unmodified lines
224 # a later state.225 plural_expr = None226 plural_expr_assignment = None227 variables = {}228 trimmed = None229 while parser.stream.current.type != 'block_end':230 if variables:231 parser.stream.expect('comma')232
10 unmodified lines
243 # expressions244 if parser.stream.current.type == 'assign':245 next(parser.stream)246 variables[name.value] = var = parser.parse_expression()247 elif trimmed is None and name.value in ('trimmed', 'notrimmed'):248 trimmed = name.value == 'trimmed'249 continue250 else:251 variables[name.value] = var = nodes.Name(name.value, 'load')252253 if plural_expr is None:
7 unmodified lines
261 num_called_num = name.value == 'num'262263 parser.stream.expect('block_end')264259 plural = plural_names = None265 plural = None266 have_plural = False267 referenced = set()268269 # now parse until endtrans or pluralize
32 unmodified lines
302 plural_expr = None303 elif plural_expr is None:304 parser.fail('pluralize without variables', lineno)305306 if trimmed is None:307 trimmed = self.environment.policies['ext.i18n.trimmed']308 if trimmed:309 singular = self._trim_whitespace(singular)310 if plural:311 plural = self._trim_whitespace(plural)312313 node = self._make_node(singular, plural, variables, plural_expr,314 bool(referenced),315 num_called_num and have_plural)316 node.set_lineno(lineno)
1 unmodified line
318 return [plural_expr_assignment, node]319 else:320 return node321322 def _trim_whitespace(self, string, _ws_re=re.compile(r'\s*\n\s*')):323 return _ws_re.sub(' ', string.strip())324325 def _parse_block(self, parser, allow_pluralize):326 """Parse until the next block tag with a given name."""327 referenced = []328 buf = []
269 unmodified lines
598 cache_size=0,599 auto_reload=False600 )601602 if getbool(options, 'trimmed'):603 environment.policies['ext.i18n.trimmed'] = True604 if getbool(options, 'newstyle_gettext'):605 environment.newstyle_gettext = True606607 source = fileobj.read().decode(options.get('encoding', 'utf-8'))
20 unmodified lines
modified:tests/test_ext.py+68 added
89 unmodified lines
90 '_': gettext,91 'gettext': gettext,92 'ngettext': ngettext93})94i18n_env_trimmed = Environment(extensions=['jinja2.ext.i18n'])95i18n_env_trimmed.policies['ext.i18n.trimmed'] = True96i18n_env_trimmed.globals.update({97 '_': gettext,98 'gettext': gettext,99 'ngettext': ngettext100})101102newstyle_i18n_env = Environment(103 loader=DictLoader(newstyle_i18n_templates),104 extensions=['jinja2.ext.i18n']
171 unmodified lines
276 def test_trans_stringformatting(self):277 tmpl = i18n_env.get_template('stringformat.html')278 assert tmpl.render(LANGUAGE='de', user_count=5) == 'Benutzer: 5'279280 def test_trimmed(self):281 tmpl = i18n_env.from_string(282 '{%- trans trimmed %} hello\n world {% endtrans -%}')283 assert tmpl.render() == 'hello world'284285 def test_trimmed_policy(self):286 s = '{%- trans %} hello\n world {% endtrans -%}'287 tmpl = i18n_env.from_string(s)288 trimmed_tmpl = i18n_env_trimmed.from_string(s)289 assert tmpl.render() == ' hello\n world '290 assert trimmed_tmpl.render() == 'hello world'291292 def test_trimmed_policy_override(self):293 tmpl = i18n_env_trimmed.from_string(294 '{%- trans notrimmed %} hello\n world {% endtrans -%}')295 assert tmpl.render() == ' hello\n world '296297 def test_trimmed_vars(self):298 tmpl = i18n_env.from_string(299 '{%- trans trimmed x="world" %} hello\n {{ x }} {% endtrans -%}')300 assert tmpl.render() == 'hello world'301302 def test_trimmed_varname_trimmed(self):303 # unlikely variable name, but when used as a variable304 # it should not enable trimming305 tmpl = i18n_env.from_string(306 '{%- trans trimmed = "world" %} hello\n {{ trimmed }} '307 '{% endtrans -%}')308 assert tmpl.render() == ' hello\n world '309310 def test_extract(self):311 from jinja2.ext import babel_extract312 source = BytesIO('''313 {{ gettext('Hello World') }}
6 unmodified lines
320 (3, 'gettext', u'Hello World', []),321 (4, 'ngettext', (u'%(users)s user', u'%(users)s users', None), [])322 ]323324 def test_extract_trimmed(self):325 from jinja2.ext import babel_extract326 source = BytesIO('''327 {{ gettext(' Hello \n World') }}328 {% trans trimmed %} Hello \n World{% endtrans %}329 {% trans trimmed %}{{ users }} \n user330 {%- pluralize %}{{ users }} \n users{% endtrans %}331 '''.encode('ascii')) # make python 3 happy332 assert list(babel_extract(source,333 ('gettext', 'ngettext', '_'), [], {})) == [334 (2, 'gettext', u' Hello \n World', []),335 (4, 'gettext', u'Hello World', []),336 (6, 'ngettext', (u'%(users)s user', u'%(users)s users', None), [])337 ]338339 def test_extract_trimmed_option(self):340 from jinja2.ext import babel_extract341 source = BytesIO('''342 {{ gettext(' Hello \n World') }}343 {% trans %} Hello \n World{% endtrans %}344 {% trans %}{{ users }} \n user345 {%- pluralize %}{{ users }} \n users{% endtrans %}346 '''.encode('ascii')) # make python 3 happy347 opts = {'trimmed': 'true'}348 assert list(babel_extract(source,349 ('gettext', 'ngettext', '_'), [], opts)) == [350 (2, 'gettext', u' Hello \n World', []),351 (4, 'gettext', u'Hello World', []),352 (6, 'ngettext', (u'%(users)s user', u'%(users)s users', None), [])353 ]354355 def test_comment_extract(self):356 from jinja2.ext import babel_extract357 source = BytesIO('''358 {# trans first #}
230 unmodified lines
modified:CHANGES+3 added
17 unmodified lines
18 last call of the method)19- Added a `namespace` function that creates a special object which allows20 attribute assignment using the `set` tag. This can be used to carry data21 across scopes, e.g. from a loop body to code that comes after the loop.22- Added a `trimmed` modifier to `{% trans %}` to strip linebreaks and23 surrounding whitespace. Also added a new policy to enable this for all24 `trans` blocks.2526Version 2.9.627-------------28(bugfix release, released on April 3rd 2017)
504 unmodified lines