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
Provenance
- Commit
e605ff1- Tree
df3d214- Author
Adrian Moennich <adrian@planetcoding.net>- Committer
Adrian <adrian@planetcoding.net>- Parent
c7dfa21
7 files changed+123 added−1 removed
modified:docs/api.rst+7 added
609 unmodified lines610 ``json.dumps_kwargs``:611 Keyword arguments to be passed to the dump function. The default is612 ``{'sort_keys': True}``.613 614+.. _ext-i18n-trimmed:615 616+``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.620+621+622 Utilities623 ---------624 625 These helper functions and classes are useful if you add custom filters or307 unmodified linesmodified:docs/extensions.rst+9 added
109 unmodified lines110 .. _Babel: http://babel.pocoo.org/111 112 .. _newstyle-gettext:113 114+Whitespace Trimming115+~~~~~~~~~~~~~~~~~~~116+117+.. versionadded:: 2.10118+119+Linebreaks and surrounding whitespace can be automatically trimmed by enabling120+the ``ext.i18n.trimmed`` :ref:`policy <ext-i18n-trimmed>`.121+122+123 Newstyle Gettext124 ~~~~~~~~~~~~~~~~125 126 .. versionadded:: 2.5224 unmodified linesmodified:docs/templates.rst+16 added
1490 unmodified lines1491 1492 {% trans ..., user_count=users|length %}...1493 {% pluralize user_count %}...{% endtrans %}1494 1495+When translating longer blocks of text, whitespace and linebreaks result in1496+rather ugly and error-prone translation strings. To avoid this, a trans block1497+can be marked as trimmed which will replace all linebreaks and the whitespace1498+surrounding them with a single space and remove leading/trailing whitespace::1499+1500+ {% trans trimmed book_title=book.title %}1501+ This is {{ book_title }}.1502+ You should read it!1503+ {% endtrans %}1504+1505+If trimming is enabled globally, the `notrimmed` modifier can be used to1506+disable it for a `trans` block.1507+1508+.. versionadded:: 2.101509+ The `trimmed` and `notrimmed` modifiers have been added.1510+1511 It's also possible to translate strings in expressions. For that purpose,1512 three functions exist:1513 1514 - `gettext`: translate a single string142 unmodified linesmodified:jinja2/defaults.py+1 added
46 unmodified lines47 '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 }53 54 55 # export all constants1 unmodified linemodified:jinja2/ext.py+19 added-1 removed
8 unmodified lines9 10 :copyright: (c) 2017 by the Jinja Team.11 :license: BSD.12 """13+import re14+15 from jinja2 import nodes16 from 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 lines224 # 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 lines243 # 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')252 253 if plural_expr is None:7 unmodified lines261 num_called_num = name.value == 'num'262 263 parser.stream.expect('block_end')264 259- plural = plural_names = None265+ plural = None266 have_plural = False267 referenced = set()268 269 # now parse until endtrans or pluralize32 unmodified lines302 plural_expr = None303 elif plural_expr is None:304 parser.fail('pluralize without variables', lineno)305 306+ 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)312+313 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 line318 return [plural_expr_assignment, node]319 else:320 return node321 322+ def _trim_whitespace(self, string, _ws_re=re.compile(r'\s*\n\s*')):323+ return _ws_re.sub(' ', string.strip())324+325 def _parse_block(self, parser, allow_pluralize):326 """Parse until the next block tag with a given name."""327 referenced = []328 buf = []269 unmodified lines598 cache_size=0,599 auto_reload=False600 )601 602+ if getbool(options, 'trimmed'):603+ environment.policies['ext.i18n.trimmed'] = True604 if getbool(options, 'newstyle_gettext'):605 environment.newstyle_gettext = True606 607 source = fileobj.read().decode(options.get('encoding', 'utf-8'))20 unmodified linesmodified:tests/test_ext.py+68 added
89 unmodified lines90 '_': gettext,91 'gettext': gettext,92 'ngettext': ngettext93 })94+i18n_env_trimmed = Environment(extensions=['jinja2.ext.i18n'])95+i18n_env_trimmed.policies['ext.i18n.trimmed'] = True96+i18n_env_trimmed.globals.update({97+ '_': gettext,98+ 'gettext': gettext,99+ 'ngettext': ngettext100+})101 102 newstyle_i18n_env = Environment(103 loader=DictLoader(newstyle_i18n_templates),104 extensions=['jinja2.ext.i18n']171 unmodified lines276 def test_trans_stringformatting(self):277 tmpl = i18n_env.get_template('stringformat.html')278 assert tmpl.render(LANGUAGE='de', user_count=5) == 'Benutzer: 5'279 280+ def test_trimmed(self):281+ tmpl = i18n_env.from_string(282+ '{%- trans trimmed %} hello\n world {% endtrans -%}')283+ assert tmpl.render() == 'hello world'284+285+ 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'291+292+ 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 '296+297+ 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'301+302+ 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 '309+310 def test_extract(self):311 from jinja2.ext import babel_extract312 source = BytesIO('''313 {{ gettext('Hello World') }}6 unmodified lines320 (3, 'gettext', u'Hello World', []),321 (4, 'ngettext', (u'%(users)s user', u'%(users)s users', None), [])322 ]323 324+ 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+ ]338+339+ 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+ ]354+355 def test_comment_extract(self):356 from jinja2.ext import babel_extract357 source = BytesIO('''358 {# trans first #}230 unmodified linesmodified:CHANGES+3 added
17 unmodified lines18 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.25 26 Version 2.9.627 -------------28 (bugfix release, released on April 3rd 2017)504 unmodified lines