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
Provenance
- Commit
b6fc38c- Tree
9110cbc- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent 1
c63243e- Parent 2
8090986
4 files changed+68 added−38 removed
modified:jinja2/compiler.py+6 added-4 removed
980 unmodified lines981 self.visit(node.step, frame)982 983 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 linesmodified:jinja2/filters.py+2 added-27 removed
13 unmodified lines14 from operator import itemgetter15 except ImportError:16 itemgetter = lambda a: lambda b: b[a]17 from urllib import urlencode, quote18-from jinja2.utils import escape, pformat18+from jinja2.utils import escape, pformat, urlize19 from jinja2.runtime import Undefined20 21 22+23 _striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')24 25 26 def contextfilter(f):259 unmodified lines286 except IndexError:287 return env.undefined_singleton288 289 289-def do_urlencode(value):290- """291- urlencode a string or directory.292-293- .. sourcecode:: jinja294-295- {{ {'foo': 'bar', 'blub': 'blah'}|urlencode }}296- -> foo=bar&blub=blah297-298- {{ '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))312-313-290 def do_jsonencode(value):291 """292 JSON dump a variable. just works if simplejson is installed.293 505 unmodified lines799 '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 linesmodified:jinja2/utils.py+59 added
6 unmodified lines7 8 :copyright: 2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11+import re12+import string13 14 15 def escape(obj, attribute=False):16 """HTML escape an object."""16 unmodified lines33 return pretty(obj, verbose=verbose)34 except ImportError:35 from pprint import pformat36 return pformat(obj)37+38+39+_word_split_re = re.compile(r'(\s+)')40+41+_punctuation_re = re.compile(42+ '^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (43+ '|'.join([re.escape(p) for p in ('(', '<', '<')]),44+ '|'.join([re.escape(p) for p in ('.', ',', ')', '>', '\n', '>')])45+ )46+)47+48+_simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')49+50+51+def 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.57+58+ If trim_url_limit is not None, the URLs in link text will be limited59+ to trim_url_limit characters.60+61+ 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 lines48 TRUNCATE = '''{{ data|truncate(15, true, ">>>") }}|\49 {{ data|truncate(15, false, ">>>") }}|\50 {{ smalldata|truncate(15) }}'''51 UPPER = '''{{ "foo"|upper }}'''52-URLENCODE = '''{{ "f#b"|urlencode }}'''52 URLIZE = '''{{ "foo http://www.example.com/ bar"|urlize }}'''53 WORDCOUNT = '''{{ "foo bar baz"|wordcount }}'''54 BLOCK = '''{% filter lower|escape %}<HEHE>{% endfilter %}'''55 CHAINING = '''{{ ['<foo>', '<bar>']|first|upper|escape }}'''145 unmodified lines201 202 203 def 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))206 207 208 def test_title(env):209 tmpl = env.from_string(TITLE)16 unmodified lines226 tmpl = env.from_string(UPPER)227 assert tmpl.render() == 'FOO'228 229 231-def test_urlencode(env):232- tmpl = env.from_string(URLENCODE)233- assert tmpl.render() == 'f%23b'234-235-230 def 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