moved `IncludedTemplate` into the regular template API, fixed more unittests
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 b5124e6 · Browse files · 9 files·+101 added−156 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+101 added−156 removed
- tests:+7 added−105 removed
- other:+94 added−51 removed
Provenance
- Commit
963f97d- Tree
e92f794- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
b5124e6
9 files changed+101 added−156 removed
modified:jinja2/compiler.py+20 added-11 removed
439 unmodified lines440 func_frame.identifiers.undeclared &441 func_frame.identifiers.declared442 )443 444- func_frame.accesses_arguments = False444+ func_frame.accesses_kwargs = False445+ func_frame.accesses_varargs = False446 func_frame.accesses_caller = False447 func_frame.arguments = args = ['l_' + x.name for x in node.args]448 448- if 'arguments' in func_frame.identifiers.undeclared:449- func_frame.accesses_arguments = True450- func_frame.identifiers.add_special('arguments')451- args.append('l_arguments')449+ if 'kwargs' in func_frame.identifiers.undeclared:450+ func_frame.accesses_kwargs = True451+ func_frame.identifiers.add_special('kwargs')452+ args.append('l_kwargs')453+ if 'varargs' in func_frame.identifiers.undeclared:454+ func_frame.accesses_varargs = True455+ func_frame.identifiers.add_special('varargs')456+ args.append('l_varargs')457 if 'caller' in func_frame.identifiers.undeclared:458 func_frame.accesses_caller = True459 func_frame.identifiers.add_special('caller')460 args.append('l_caller')141 unmodified lines602 if node.target is not None:603 self.writeline('l_%s = ' % node.target, node)604 if frame.toplevel:605 self.write('context[%r] = ' % node.target)601- self.write('IncludedTemplate(environment, context, ')606+ self.write('environment.get_template(')607 self.visit(node.template, frame)603- self.write(')')608+ self.write(', %r).include(context)' % self.name)609 return610 611 self.writeline('included_template = environment.get_template(', node)612 self.visit(node.template, frame)608- self.write(')')613+ self.write(', %r)' % self.name)614 if frame.toplevel:615 self.writeline('included_context = included_template.new_context('616 'context.get_root())')617 self.writeline('for event in included_template.root_render_func('115 unmodified lines733 (node.name, node.name, arg_tuple))734 for arg in node.defaults:735 self.visit(arg, macro_frame)736 self.write(', ')732- self.write('), %s, %s)' % (733- macro_frame.accesses_arguments and '1' or '0',737+ self.write('), %s, %s, %s)' % (738+ macro_frame.accesses_kwargs and '1' or '0',739+ macro_frame.accesses_varargs and '1' or '0',740 macro_frame.accesses_caller and '1' or '0'741 ))742 743 def visit_CallBlock(self, node, frame):14 unmodified lines758 arg_tuple)759 for arg in node.defaults:760 self.visit(arg)761 self.write(', ')756- self.write('), %s, 0)' % (call_frame.accesses_arguments and '1' or '0'))762+ self.write('), %s, %s, 0)' % (763+ call_frame.accesses_kwargs and '1' or '0',764+ call_frame.accesses_varargs and '1' or '0'765+ ))766 if frame.buffer is None:767 self.writeline('yield ', node)768 else:769 self.writeline('%s.append(' % frame.buffer, node)306 unmodified linesmodified:jinja2/environment.py+29 added
345 unmodified lines346 """Create a new template context for this template."""347 return TemplateContext(self.environment, dict(self.globals, **vars),348 self.name, self.blocks)349 350+ def include(self, context=None):351+ """Include this template."""352+ if context is None:353+ context = self.new_context({})354+ elif isinstance(context, TemplateContext):355+ context = self.new_context(context.get_root())356+ else:357+ context = self.new_context(context)358+ return IncludedTemplate(self, context)359+360 def get_corresponding_lineno(self, lineno):361 """Return the source line number of a line number in the362 generated bytecode as they are not in sync.363 """21 unmodified lines385 self.name or '<from string>'386 )387 388 389+class IncludedTemplate(object):390+ """Represents an included template."""391+392+ def __init__(self, template, context):393+ self._template = template394+ self._name = template.name395+ self._rendered_body = u''.join(template.root_render_func(context))396+ self._context = context.get_exported()397+398+ __getitem__ = lambda x, n: x._context[n]399+ __html__ = __unicode__ = lambda x: x._rendered_body400+401+ def __repr__(self):402+ return '<%s %r>' % (403+ self.__class__.__name__,404+ self._name405+ )406+407+408 class TemplateStream(object):409 """This class wraps a generator returned from `Template.generate` so that410 it's possible to buffer multiple elements so that it's possible to return411 them from a WSGI application which flushes after each iteration.48 unmodified linesmodified:jinja2/filters.py+21 added-5 removed
376 unmodified lines377 (line, u' \n'[(len(line)-line.rfind('\n') - 1 +378 len(word.split('\n', 1)[0]) >= pos)],379 word), s.split(' '))380 381+382 def do_wordcount(s):383 """Count the words in that string."""384 return len(s.split())385 386+387 def do_int(value, default=0):388 """Convert the value into an integer. If the389 conversion doesn't work it will return ``0``. You can390 override this default using the first parameter.173 unmodified lines564 {% endfor %}</ul></li>565 {% endfor %}566 </ul>567 568+ Additionally it's possible to use tuple unpacking for the grouper and569+ list:570+571+ .. sourcecode:: html+jinja572+573+ <ul>574+ {% for grouper, list in persons|groupby('gender') %}575+ ...576+ {% endfor %}577+ </ul>578+579 As you can see the item we're grouping by is stored in the `grouper`580 attribute and the `list` contains all the objects that have this grouper581 in common.582 """583 expr = lambda x: environment.subscribe(x, attribute)571- return sorted([{572- 'grouper': a,573- 'list': b574- } for a, b in groupby(sorted(value, key=expr), expr)],575- key=itemgetter('grouper'))584+ return sorted(map(_GroupTuple, groupby(sorted(value, key=expr), expr)),585+ key=itemgetter('grouper'))586 587 588+class _GroupTuple(tuple):589+ __slots__ = ()590+ grouper = property(itemgetter(0))591+ list = property(itemgetter(1))592+593+594 FILTERS = {595 'replace': do_replace,596 'upper': do_upper,597 'lower': do_lower,40 unmodified linesmodified:jinja2/loaders.py+8 added-5 removed
124 unmodified lines125 self.package_name = package_name126 self.package_path = package_path127 128 def get_source(self, environment, template):129- path = '/'.join(split_template_path(template))129+ pieces = split_template_path(template)130+ path = '/'.join((self.package_path,) + tuple(pieces))131 if not self._pkg.resource_exists(self.package_name, path):132 raise TemplateNotFound(template)133 return self._pkg.resource_string(self.package_name, path), None, None134 12 unmodified lines147 148 149 class FunctionLoader(BaseLoader):150 """A loader that is passed a function which does the loading. The150- function has to work like a `get_source` method but the return value for151- not existing templates may be `None` instead of a `TemplateNotFound`152- exception.151+ function becomes the name of the template passed and has to return either152+ an unicode string with the template source, a tuple in the form ``(source,153+ filename, uptodatefunc)`` or `None` if the template does not exist.154 """155 156 def __init__(self, load_func, cache_size=50, auto_reload=True):157 BaseLoader.__init__(self, cache_size, auto_reload)158 self.load_func = load_func159 160 def get_source(self, environment, template):160- rv = self.load_func(environment, template)161+ rv = self.load_func(template)162 if rv is None:163 raise TemplateNotFound(template)164+ elif isinstance(rv, basestring):165+ return rv, None, None166 return rv167 168 169 class PrefixLoader(BaseLoader):39 unmodified linesmodified:jinja2/runtime.py+15 added-28 removed
12 unmodified lines13 from jinja2.exceptions import UndefinedError14 15 16 __all__ = ['LoopContext', 'StaticLoopContext', 'TemplateContext',17- 'Macro', 'IncludedTemplate', 'Markup']17+ 'Macro', 'Markup']18 19 20 class TemplateContext(object):21 """Holds the variables of the local template or of the global one. It's74 unmodified lines96 97 def __repr__(self):98 return '<%s %s of %r>' % (99 self.__class__.__name__,100- dict.__repr__(self),100+ repr(self.get_all()),101 self.name102 )103 104 14 unmodified lines119 self.name120 )121 122 123-class IncludedTemplate(object):124- """Represents an included template."""125-126- def __init__(self, environment, context, template):127- template = environment.get_template(template)128- context = template.new_context(context.get_root())129- self._name = template.name130- self._rendered_body = u''.join(template.root_render_func(context))131- self._context = context.get_exported()132-133- __getitem__ = lambda x, n: x._context[n]134- __html__ = __unicode__ = lambda x: x._rendered_body135-136- def __repr__(self):137- return '<%s %r>' % (138- self.__class__.__name__,139- self._name140- )141-142-123 class LoopContextBase(object):124 """Helper for extended iteration."""125 126 def __init__(self, iterable, parent=None):80 unmodified lines207 208 class Macro(object):209 """Wraps a macro."""210 231- def __init__(self, environment, func, name, arguments, defaults, catch_all, caller):211+ def __init__(self, environment, func, name, arguments, defaults,212+ catch_kwargs, catch_varargs, caller):213 self._environment = environment214 self._func = func215 self.name = name216 self.arguments = arguments217 self.defaults = defaults237- self.catch_all = catch_all218+ self.catch_kwargs = catch_kwargs219+ self.catch_varargs = catch_varargs220 self.caller = caller221 222 def __call__(self, *args, **kwargs):223 arg_count = len(self.arguments)242- if len(args) > arg_count:243- raise TypeError('macro %r takes not more than %d argument(s).' %224+ if not self.catch_varargs and len(args) > arg_count:225+ raise TypeError('macro %r takes not more than %d argument(s)' %226 (self.name, len(self.arguments)))227 arguments = {}228 for idx, name in enumerate(self.arguments):229 try:12 unmodified lines242 caller = kwargs.pop('caller', None)243 if caller is None:244 caller = self._environment.undefined('No caller defined')245 arguments['l_caller'] = caller264- if self.catch_all:265- arguments['l_arguments'] = kwargs246+ if self.catch_kwargs:247+ arguments['l_kwargs'] = kwargs248+ elif kwargs:249+ raise TypeError('macro %r takes no keyword argument %r' %250+ (self.name, iter(kwargs).next()))251+ if self.catch_varargs:252+ arguments['l_varargs'] = args[arg_count:]253 return self._func(**arguments)254 255 def __repr__(self):256 return '<%s %s>' % (84 unmodified linesmodified:jinja2/visitor.py+1 added-2 removed
22 unmodified lines23 (return value `None`) the `generic_visit` visitor is used instead.24 """25 26 def get_visitor(self, node):27- """28- Return the visitor function for this node or `None` if no visitor27+ """Return the visitor function for this node or `None` if no visitor28 exists for this node. In that case the generic visit function is29 used instead.30 """31 method = 'visit_' + node.__class__.__name__56 unmodified linesdeleted:tests/loaderres/templates/brokenimport.html-1 removed
1{% extends "missing.html" %}modified:tests/test_loaders.py+5 added-102 removed
5 unmodified lines6 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8 """9 10+from py.test import raises11 import time12 import tempfile13 from jinja2 import Environment, loaders14 from jinja2.exceptions import TemplateNotFound6 unmodified lines21 package_loader = loaders.PackageLoader('loaderres', 'templates')22 23 filesystem_loader = loaders.FileSystemLoader('loaderres/templates')24 24-memcached_loader = loaders.MemcachedFileSystemLoader('loaderres/templates')25-25 function_loader = loaders.FunctionLoader({'justfunction.html': 'FOO'}.get)26 27 choice_loader = loaders.ChoiceLoader([dict_loader, package_loader])28 29 31-class FakeLoader(loaders.BaseLoader):32- local_attr = 4233-34-30 def test_dict_loader():31 env = Environment(loader=dict_loader)32 tmpl = env.get_template('justdict.html')33 assert tmpl.render().strip() == 'FOO'6 unmodified lines40 41 42 def test_package_loader():43 env = Environment(loader=package_loader)49- for x in xrange(2):50- tmpl = env.get_template('test.html')51- assert tmpl.render().strip() == 'BAR'52- try:44+ tmpl = env.get_template('test.html')45+ assert tmpl.render().strip() == 'BAR'46+ raises(TemplateNotFound, lambda: env.get_template('missing.html'))53- env.get_template('missing.html')54- except TemplateNotFound:55- pass56- else:57- raise AssertionError('expected template exception')47 59- # second run in native mode (no pkg_resources)60- package_loader.force_native = True61- del package_loader._load_func48 63-49 def test_filesystem_loader():50 env = Environment(loader=filesystem_loader)51 tmpl = env.get_template('test.html')52 assert tmpl.render().strip() == 'BAR'53 tmpl = env.get_template('foo/test.html')54 assert tmpl.render().strip() == 'FOO'70- try:71- env.get_template('missing.html')72- except TemplateNotFound:73- pass74- else:75- raise AssertionError('expected template exception')55+ raises(TemplateNotFound, lambda: env.get_template('missing.html'))56 57 78-def test_memcached_loader():79- env = Environment(loader=memcached_loader)80- tmpl = env.get_template('test.html')81- assert tmpl.render().strip() == 'BAR'82- tmpl = env.get_template('foo/test.html')83- assert tmpl.render().strip() == 'FOO'84- try:85- env.get_template('missing.html')86- except TemplateNotFound:87- pass88- else:89- raise AssertionError('expected template exception')90-91-58 def test_choice_loader():59 env = Environment(loader=choice_loader)60 tmpl = env.get_template('justdict.html')61 assert tmpl.render().strip() == 'FOO'5 unmodified lines67 pass68 else:69 raise AssertionError('expected template exception')70 105- # this should raise an TemplateNotFound error with the106- # correct name107- try:108- env.get_template('brokenimport.html')109- except TemplateNotFound, e:110- assert e.name == 'missing.html'111- else:112- raise AssertionError('expected exception')71 114-72 def test_function_loader():73 env = Environment(loader=function_loader)74 tmpl = env.get_template('justfunction.html')75 assert tmpl.render().strip() == 'FOO'2 unmodified lines78 except TemplateNotFound:79 pass80 else:81 raise AssertionError('expected template exception')125-126-127-def test_loader_redirect():128- env = Environment(loader=FakeLoader())129- assert env.loader.local_attr == 42130- assert env.loader.get_source131- assert env.loader.load132-133-134-class MemcacheTestingLoader(loaders.CachedLoaderMixin, loaders.BaseLoader):135-136- def __init__(self, enable):137- loaders.CachedLoaderMixin.__init__(self, enable, 40, None, True, 'foo')138- self.times = {}139- self.idx = 0140-141- def touch(self, name):142- self.times[name] = time.time()143-144- def get_source(self, environment, name, parent):145- self.touch(name)146- self.idx += 1147- return 'Template %s (%d)' % (name, self.idx)148-149- def check_source_changed(self, environment, name):150- if name in self.times:151- return self.times[name]152- return -1153-154-155-memcache_env = Environment(loader=MemcacheTestingLoader(True))156-no_memcache_env = Environment(loader=MemcacheTestingLoader(False))157-158-159-test_memcaching = r'''160->>> not_caching = MODULE.no_memcache_env.loader161->>> caching = MODULE.memcache_env.loader162->>> touch = caching.touch163-164->>> tmpl1 = not_caching.load('test.html')165->>> tmpl2 = not_caching.load('test.html')166->>> tmpl1 == tmpl2167-False168-169->>> tmpl1 = caching.load('test.html')170->>> tmpl2 = caching.load('test.html')171->>> tmpl1 == tmpl2172-True173-174->>> touch('test.html')175->>> tmpl2 = caching.load('test.html')176->>> tmpl1 == tmpl2177-False178-'''modified:tests/test_macros.py+2 added-2 removed
14 unmodified lines15 SCOPING = '''\16 {% macro level1(data1) %}17 {% macro level2(data2) %}{{ data1 }}|{{ data2 }}{% endmacro %}18 {{ level2('bar') }}{% endmacro %}19-{{ level1('foo') }}|{{ level2('bar') }}\19+{{ level1('foo') }}\20 '''21 22 ARGUMENTS = '''\23 {% macro m(a, b, c='c', d='d') %}{{ a }}|{{ b }}|{{ c }}|{{ d }}{% endmacro %}30 unmodified lines54 55 56 def test_scoping(env):57 tmpl = env.from_string(SCOPING)58- assert tmpl.render() == 'foo|bar|'58+ assert tmpl.render() == 'foo|bar'59 60 61 def test_arguments(env):62 tmpl = env.from_string(ARGUMENTS)26 unmodified lines