Skip to content
Myr

Automated merge with ssh://team@pocoo.org/jinja2-main

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 · parents c63243e, 8090986 · Browse files · 4 files+68 added−38 removed
This commit

State

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

Diff stats

4 files+68 added−38 removed

  • tests:+1 added−7 removed
  • other:+67 added−31 removed

4 files+68 added−38 removed

modified:jinja2/compiler.py+6 added-4 removed
980 unmodified lines
981 self.visit(node.step, frame)982983 def visit_Filter(self, node, frame, initial=None):984 self.write('f_%s(' % node.name)985 if initial is not None:985 func = self.environment.filters.get(node.name)986 if getattr(func, 'contextfilter', False):987 self.write('context, ')988 if isinstance(node.node, nodes.Filter):989 self.visit_Filter(node.node, frame, initial)990 elif node.node is None:991 self.write(initial)992 else:988 func = self.environment.filters.get(node.name)989 if getattr(func, 'contextfilter', False):990 self.write('context, ')993 self.visit(node.node, frame)994 self.signature(node, frame)995 self.write(')')996
39 unmodified lines
modified:jinja2/filters.py+2 added-27 removed
13 unmodified lines
14 from operator import itemgetter15except ImportError:16 itemgetter = lambda a: lambda b: b[a]17from urllib import urlencode, quote18from jinja2.utils import escape, pformat18from jinja2.utils import escape, pformat, urlize19from jinja2.runtime import Undefined20212223_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')242526def contextfilter(f):
259 unmodified lines
286 except IndexError:287 return env.undefined_singleton288289289def do_urlencode(value):290 """291 urlencode a string or directory.292293 .. sourcecode:: jinja294295 {{ {'foo': 'bar', 'blub': 'blah'}|urlencode }}296 -> foo=bar&blub=blah297298 {{ 'Hello World' }}299 -> Hello%20World300 """301 if isinstance(value, dict):302 tmp = {}303 for key, value in value.iteritems():304 # XXX env.charset?305 key = unicode(key).encode(env.charset)306 value = unicode(value).encode(env.charset)307 tmp[key] = value308 return urlencode(tmp)309 else:310 # XXX: env.charset?311 return quote(unicode(value).encode(env.charset))312313290def do_jsonencode(value):291 """292 JSON dump a variable. just works if simplejson is installed.293
505 unmodified lines
799 'capitalize': do_capitalize,800 'first': do_first,801 'last': do_last,802 'random': do_random,827 'urlencode': do_urlencode,803 'jsonencode': do_jsonencode,804 'filesizeformat': do_filesizeformat,805 'pprint': do_pprint,806 'indent': do_indent,
24 unmodified lines
modified:jinja2/utils.py+59 added
6 unmodified lines
78 :copyright: 2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import re12import string131415def escape(obj, attribute=False):16 """HTML escape an object."""
16 unmodified lines
33 return pretty(obj, verbose=verbose)34 except ImportError:35 from pprint import pformat36 return pformat(obj)373839_word_split_re = re.compile(r'(\s+)')4041_punctuation_re = re.compile(42 '^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (43 '|'.join([re.escape(p) for p in ('(', '<', '&lt;')]),44 '|'.join([re.escape(p) for p in ('.', ',', ')', '>', '\n', '&gt;')])45 )46)4748_simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')495051def urlize(text, trim_url_limit=None, nofollow=False):52 """53 Converts any URLs in text into clickable links. Works on http://,54 https:// and www. links. Links can have trailing punctuation (periods,55 commas, close-parens) and leading punctuation (opening parens) and56 it'll still do the right thing.5758 If trim_url_limit is not None, the URLs in link text will be limited59 to trim_url_limit characters.6061 If nofollow is True, the URLs in link text will get a rel="nofollow"62 attribute.63 """64 trim_url = lambda x, limit=trim_url_limit: limit is not None \65 and (x[:limit] + (len(x) >=limit and '...'66 or '')) or x67 words = _word_split_re.split(text)68 nofollow_attr = nofollow and ' rel="nofollow"' or ''69 for i, word in enumerate(words):70 match = _punctuation_re.match(word)71 if match:72 lead, middle, trail = match.groups()73 if middle.startswith('www.') or (74 '@' not in middle and75 not middle.startswith('http://') and76 len(middle) > 0 and77 middle[0] in string.letters + string.digits and (78 middle.endswith('.org') or79 middle.endswith('.net') or80 middle.endswith('.com')81 )):82 middle = '<a href="http://%s"%s>%s</a>' % (middle,83 nofollow_attr, trim_url(middle))84 if middle.startswith('http://') or \85 middle.startswith('https://'):86 middle = '<a href="%s"%s>%s</a>' % (middle,87 nofollow_attr, trim_url(middle))88 if '@' in middle and not middle.startswith('www.') and \89 not ':' in middle and _simple_email_re.match(middle):90 middle = '<a href="mailto:%s">%s</a>' % (middle, middle)91 if lead + middle + trail != word:92 words[i] = lead + middle + trail93 return u''.join(words)
modified:tests/test_filters.py+1 added-7 removed
47 unmodified lines
48TRUNCATE = '''{{ data|truncate(15, true, ">>>") }}|\49{{ data|truncate(15, false, ">>>") }}|\50{{ smalldata|truncate(15) }}'''51UPPER = '''{{ "foo"|upper }}'''52URLENCODE = '''{{ "f#b"|urlencode }}'''52URLIZE = '''{{ "foo http://www.example.com/ bar"|urlize }}'''53WORDCOUNT = '''{{ "foo bar baz"|wordcount }}'''54BLOCK = '''{% filter lower|escape %}<HEHE>{% endfilter %}'''55CHAINING = '''{{ ['<foo>', '<bar>']|first|upper|escape }}'''
145 unmodified lines
201202203def test_string(env):204 tmpl = env.from_string(STRING)206 assert tmpl.render(foo=range(10)) == str(range(10))205 assert tmpl.render(foo=range(10)) == unicode(xrange(10))206207208def test_title(env):209 tmpl = env.from_string(TITLE)
16 unmodified lines
226 tmpl = env.from_string(UPPER)227 assert tmpl.render() == 'FOO'228229231def test_urlencode(env):232 tmpl = env.from_string(URLENCODE)233 assert tmpl.render() == 'f%23b'234235230def test_urlize(env):231 tmpl = env.from_string(URLIZE)232 assert tmpl.render() == 'foo <a href="http://www.example.com/">'\233 'http://www.example.com/</a> bar'
58 unmodified lines