From: Francisco Jiménez Cabrera Date: Wed, 1 Mar 2017 23:10:29 +0000 (+0100) Subject: Ignore empty lines in indent filter X-Git-Tag: 2.10~13^2~1 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=bb8ef40957efd368fb3de2b2dc5a2d0c14ae5eae;p=thirdparty%2Fjinja.git Ignore empty lines in indent filter --- diff --git a/jinja2/filters.py b/jinja2/filters.py index cb377283..aec4843c 100644 --- a/jinja2/filters.py +++ b/jinja2/filters.py @@ -11,6 +11,7 @@ import re import math import random +import warnings from itertools import groupby, chain from collections import namedtuple @@ -525,7 +526,7 @@ def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False, return rv -def do_indent(s, width=4, indentfirst=False): +def do_indent(s, width=4, indent_first=False, indent_blank_lines=False, indentfirst=None): """Return a copy of the passed string, each line indented by 4 spaces. The first line is not indented. If you want to change the number of spaces or indent the first line too @@ -536,9 +537,20 @@ def do_indent(s, width=4, indentfirst=False): {{ mytext|indent(2, true) }} indent by two spaces and indent the first line too. """ + if indentfirst is not None: + warnings.warn('The use of indentfirst is obsolete. ' + 'You should use indent_first instead.', DeprecationWarning) + indent_first = indentfirst + s += '\n' # this quirk is necessary for splitlines method indention = u' ' * width - rv = (u'\n' + indention).join(s.splitlines()) - if indentfirst: + if indent_blank_lines: + rv = (u'\n' + indention).join(s.splitlines()) + else: + lines = s.splitlines() + rv = lines.pop(0) + if lines: + rv += u'\n' + u'\n'.join(indention + line if line else line for line in lines) + if indent_first: rv = indention + rv return rv diff --git a/tests/test_filters.py b/tests/test_filters.py index 84e77d9d..233b27fe 100644 --- a/tests/test_filters.py +++ b/tests/test_filters.py @@ -136,11 +136,15 @@ class TestFilter(object): assert out == 'a|b' def test_indent(self, env): - tmpl = env.from_string('{{ foo|indent(2) }}|{{ foo|indent(2, true) }}') - text = '\n'.join([' '.join(['foo', 'bar'] * 2)] * 2) - out = tmpl.render(foo=text) - assert out == ('foo bar foo bar\n foo bar foo bar| ' - 'foo bar foo bar\n foo bar foo bar') + text = '\n'.join(['', 'foo bar', '']) + tmpl = env.from_string('{{ foo|indent(2, false, false) }}') + assert tmpl.render(foo=text) == '\n foo bar\n' + tmpl = env.from_string('{{ foo|indent(1, false, true) }}') + assert tmpl.render(foo=text) == '\n foo bar\n ' + tmpl = env.from_string('{{ foo|indent(1, true, false) }}') + assert tmpl.render(foo=text) == ' \n foo bar\n' + tmpl = env.from_string('{{ foo|indent(1, true, true) }}') + assert tmpl.render(foo=text) == ' \n foo bar\n ' def test_int(self, env): class IntIsh(object):