[svn] checked in today's jinja changes which i forgot to commit
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 · parent 10dae5b · Browse files · 8 files·+124 added−15 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+124 added−15 removed
- other:+124 added−15 removed
Provenance
- Commit
a5c8d58- Tree
83dd6a2- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
10dae5b
8 files changed+124 added−15 removed
modified:docs/src/designerdoc.txt+50 added
156 unmodified lines157 generate 10 HTML paragraphs between 50 and 200 words.158 159 *new in Jinja 1.1*160 161+`watchchanges`162+163+ Jinja does not provide an django like ``{% ifchanged %}`` tag. As164+ replacement for this tag there is a special function in the namespace165+ called `watchchanges`.166+167+ You can use it like this:168+169+ .. sourcecode:: html+jinja170+171+ {% for changed, article in watchchanges(articles, 'date', 'day') %}172+ {% if changed %}<h3>{{ articles.date.day }}</h3>{% endif %}173+ <h4>{{ article.title|e }}</h4>174+ <p>{{ article.body|e }}</p>175+ {% endif %}176+177+ For each iteration `watchchanges` will check the given attribute. If it178+ changed to the former iteration the first yielded item (in this example179+ it's called `changed`) will be `true`, else `false`.180+181+ In this example `articles` is a list of articles for the template with182+ an attribute called `date.day` which represents the current day. To only183+ add a new day headline if the day has changed `watchchanges` is now told184+ to check `articles.date.days`.185+186+ If you want to observe more than one attribute you can provide pairs:187+188+ .. sourcecode:: html+jinja189+190+ {% for changed, item in watchchanges(foo, ('a', 'b'), ('a', 'c')) %}191+ ...192+ {% endfor %}193+194+ Note that if you want to watch two first level attributes you have to195+ either use the list syntax `[]` or add a colon:196+197+ .. sourcecode:: html+jinja198+199+ {% for changed, item in watchchanges(foo, ['a'], ('b',)) %}200+ ...201+ {% endfor %}202+203+ otherwise Jinja cannot differ between a pair of parentheses to group204+ expressions or the sequence syntax.205+206+ If you don't provide any arguments the value of the variable itself207+ is checked.208+209+ *new in Jinja 1.1*210+211 Loops212 =====213 214 To iterate over a sequence, you can use the `for` loop. It basically looks like a629 unmodified linesmodified:jinja/translators/python.py+4 added-1 removed
444 unmodified lines445 446 # handle real loop code447 self.indention += 1448 write(self.nodeinfo(node.body))449+ if node.body:449- buf.append(self.handle_node(node.body) or self.indent('pass'))450+ buf.append(self.handle_node(node.body))451+ else:452+ write('pass')453 self.indention -= 1454 455 # else part of loop456 if node.else_:477 unmodified linesmodified:jinja/defaults.py+4 added-2 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 from jinja.filters import FILTERS as DEFAULT_FILTERS12 from jinja.tests import TESTS as DEFAULT_TESTS13-from jinja.utils import debug_context, safe_range, generate_lorem_ipsum13+from jinja.utils import debug_context, safe_range, generate_lorem_ipsum, \14+ watch_changes15 16 17 DEFAULT_NAMESPACE = {18 'range': safe_range,19 'debug': debug_context,19- 'lipsum': generate_lorem_ipsum20+ 'lipsum': generate_lorem_ipsum,21+ 'watchchanges': watch_changes22 }modified:jinja/environment.py+10 added
180 unmodified lines181 except (AttributeError, SecurityException):182 pass183 return Undefined184 185+ def get_attributes(self, obj, attributes):186+ """187+ Get some attributes from an object. If attributes is an188+ empty sequence the object is returned as it.189+ """190+ get = self.get_attribute191+ for name in attributes:192+ obj = get(obj, name)193+ return obj194+195 def call_function(self, f, context, args, kwargs, dyn_args, dyn_kwargs):196 """197 Function call helper. Called for all functions that are passed198 any arguments.36 unmodified linesmodified:jinja/lexer.py+6 added-4 removed
109 unmodified lines110 (c('.+'), 'data', None)111 ],112 # comments113 'comment_begin': [114- (c(r'(.*?)(\-%s\s*|%s)' % (114+ (c(r'(.*?)((?:\-%s\s*|%s)%s)' % (115 e(environment.comment_end_string),116- e(environment.comment_end_string)116+ e(environment.comment_end_string),117+ block_suffix_re118 )), ('comment', 'comment_end'), '#pop'),119 (c('(.)'), (Failure('Missing end of comment tag'),), None)120 ],121 # directives122 'block_begin': [122- (c('\-%s\s*|%s' % (123+ (c('(?:\-%s\s*|%s)%s' % (124 e(environment.block_end_string),124- e(environment.block_end_string)125+ e(environment.block_end_string),126+ block_suffix_re127 )), 'block_end', '#pop'),128 ] + tag_rules,129 # variables130 'variable_begin': [136 unmodified linesmodified:jinja/nodes.py+2 added-2 removed
98 unmodified lines99 def get_items(self):100 return self.extends is not None and [self.extends] or []101 102 def __repr__(self):103- return 'Template(%r, %r, %r)' % (103+ return 'Template(%r, %r, %s)' % (104 self.filename,105 self.extends,106- NodeList.__repr__(self)106+ list.__repr__(self)107 )108 109 110 class ForLoop(Node):239 unmodified linesmodified:jinja/parser.py+11 added-3 removed
473 unmodified lines474 """475 tokens = []476 for t_lineno, t_token, t_data in gen:477 if t_token == 'string':478+ # because some libraries have problems with unicode479+ # objects we do some lazy unicode processing here.480+ # if a string is ASCII only we yield it as string481+ # in other cases as unicode. This works around482+ # problems with datetimeobj.strftime()483+ try:484+ str(t_data)485+ except UnicodeError:478- tokens.append('u' + t_data)479- else:480- tokens.append(t_data)486+ tokens.append('u' + t_data)487+ continue488+ tokens.append(t_data)489 source = '\xef\xbb\xbf' + (template % (u' '.join(tokens)).490 encode('utf-8'))491 try:492 ast = parse(source, 'exec')151 unmodified linesmodified:jinja/utils.py+37 added-3 removed
27 unmodified lines28 29 #: number of maximal range items30 MAX_RANGE = 100000031 32-_integer_re = re.compile('^(\d+)$')33-32 _word_split_re = re.compile(r'(\s+)')33 34 _punctuation_re = re.compile(35 '^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (160 unmodified lines196 return u'\n\n'.join(result)197 return u'\n'.join([u'<p>%s</p>' % escape(x) for x in result])198 199 200+def watch_changes(env, context, iterable, *attributes):201+ """202+ Wise replacement for ``{% ifchanged %}``.203+ """204+ # find the attributes to watch205+ if attributes:206+ tests = []207+ tmp = []208+ for attribute in attributes:209+ if isinstance(attribute, (str, unicode, int, long, bool)):210+ tmp.append(attribute)211+ else:212+ tests.append(tuple(attribute))213+ if tmp:214+ tests.append(tuple(attribute))215+ last = tuple([object() for x in tests])216+ # or no attributes if we watch the object itself217+ else:218+ tests = None219+ last = object()220+221+ # iterate trough it and keep check the attributes or values222+ for item in iterable:223+ if tests is None:224+ cur = item225+ else:226+ cur = tuple([env.get_attributes(item, x) for x in tests])227+ if cur != last:228+ changed = True229+ last = cur230+ else:231+ changed = False232+ yield changed, item233+watch_changes.jinja_context_callable = True234+235+202-# python2.4 and lower has a bug regarding joining of broken generators236+# python2.4 and lower has a bug regarding joining of broken generators.237 # because of the runtime debugging system we have to keep track of the238 # number of frames to skip. that's what RUNTIME_EXCEPTION_OFFSET is for.239 if sys.version_info < (2, 5):240 capture_generator = lambda gen: u''.join(tuple(gen))254 unmodified lines