Skip to content
Myr

inheritance uses a less awkward hack for contexts now and subclassing templates is possible

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 07a21ba · Browse files · 13 files+416 added−266 removed
This commit

State

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

Diff stats

13 files+416 added−266 removed

  • tests:+4 added−31 removed
  • other:+412 added−235 removed

13 files+416 added−266 removed

modified:jinja2/__init__.py+23 added-39 removed
1 unmodified line
2"""3 jinja24 ~~~~~~56 Jinja is a `sandboxed`_ template engine written in pure Python. It7 provides a `Django`_ like non-XML syntax and compiles templates into8 executable python code. It's basically a combination of Django templates9 and python code.6 Jinja2 is a template engine written in pure Python. It provides a7 Django inspired non-XML syntax but supports inline expressions and8 an optional sandboxed environment.910 Nutshell11 --------1214 Here a small example of a Jinja template::13 Here a small example of a Jinja2 template::1415 {% extends 'base.html' %}16 {% block title %}Memberlist{% endblock %}17 {% block content %}18 <ul>19 {% for user in users %}21 <li><a href="{{ user.url|e }}">{{ user.username|e }}</a></li>20 <li><a href="{{ user.url }}">{{ user.username }}</a></li>21 {% endfor %}22 </ul>23 {% endblock %}2426 Philosophy27 ----------2529 Application logic is for the controller but don't try to make the life30 for the template designer too hard by giving him too few functionality.3132 For more informations visit the new `jinja webpage`_ and `documentation`_.3334 Note35 ----3637 This is the Jinja 1.0 release which is completely incompatible with the38 old "pre 1.0" branch. The old branch will still receive security updates39 and bugfixes but the 1.0 branch will be the only version that receives40 support.4142 If you have an application that uses Jinja 0.9 and won't be updated in43 the near future the best idea is to ship a Jinja 0.9 checkout together44 with the application.4546 The `Jinja tip`_ is installable via `easy_install` with ``easy_install47 Jinja==dev``.4849 .. _sandboxed: http://en.wikipedia.org/wiki/Sandbox_(computer_security)50 .. _Django: http://www.djangoproject.com/51 .. _jinja webpage: http://jinja.pocoo.org/52 .. _documentation: http://jinja.pocoo.org/documentation/index.html53 .. _Jinja tip: http://dev.pocoo.org/hg/jinja-main/archive/tip.tar.gz#egg=Jinja-dev545556 :copyright: 2008 by Armin Ronacher.26 :copyright: 2008 by Armin Ronacher, Christoph Hack.27 :license: BSD, see LICENSE for more details.28"""29__docformat__ = 'restructuredtext en'30try:31 __version__ = __import__('pkg_resources') \32 .get_distribution('Jinja2').version33except:34 __version__ = 'unknown'3536# high level interface59from jinja2.environment import Environment37from jinja2.environment import Environment, Template3839# loaders40from jinja2.loaders import BaseLoader, FileSystemLoader, PackageLoader, \61 DictLoader41 DictLoader, FunctionLoader, PrefixLoader, ChoiceLoader4243# undefined types44from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined4546# decorators and public utilities47from jinja2.filters import environmentfilter, contextfilter64from jinja2.utils import Markup, escape, contextfunction48from jinja2.utils import Markup, escape, environmentfunction, contextfunction
modified:jinja2/compiler.py+34 added-26 removed
473 unmodified lines
474 self.name)475 self.blocks[block.name] = block476477 # generate the root render function.478 self.writeline('def root(globals, environment=environment'479 ', standalone=False):', extra=1)480 self.indent()481 self.writeline('context = TemplateContext(environment, globals, %r, '482 'blocks, standalone)' % self.name)478 self.writeline('def root(context, environment=environment'479 '):', extra=1)480 if have_extends:481 self.indent()484 self.writeline('parent_root = None')485 self.outdent()482 self.writeline('parent_template = None')483 self.outdent()484485 # process the root486 frame = Frame()487 frame.inspect(node.body)488 frame.toplevel = frame.rootlevel = True489 self.indent()490 self.pull_locals(frame, indent=False)493 self.writeline('yield context')491 self.blockvisit(node.body, frame, indent=False)492 self.outdent()493494 # make sure that the parent root is called.495 if have_extends:496 if not self.has_known_extends:497 self.indent()501 self.writeline('if parent_root is not None:')498 self.writeline('if parent_template is not None:')499 self.indent()503 self.writeline('stream = parent_root(context)')504 self.writeline('stream.next()')505 self.writeline('for event in stream:')500 self.writeline('for event in parent_template.'501 'root_render_func(context):')502 self.indent()503 self.writeline('yield event')508 self.outdent(1 + self.has_known_extends)504 self.outdent(2 + (not self.has_known_extends))505506 # at this point we now have the blocks collected and can visit them too.507 for name, block in self.blocks.iteritems():508 block_frame = Frame()509 block_frame.inspect(block.body)510 block_frame.block = name511 block_frame.identifiers.add_special('super')516 block_frame.name_overrides['super'] = 'context.super(%r)' % name512 block_frame.name_overrides['super'] = 'context.super(%r, ' \513 'block_%s)' % (name, name)514 self.writeline('def block_%s(context, environment=environment):'515 % name, block, 1)516 self.pull_locals(block_frame)517 self.blockvisit(block.body, block_frame)
2 unmodified lines
520 for x in self.blocks),521 extra=1)522523 # add a function that returns the debug info527 self.writeline('def get_debug_info():', extra=1)528 self.indent()529 self.writeline('return %r' % self.debug_info)524 self.writeline('debug_info = %r' % '&'.join('%s=%s' % x for x525 in self.debug_info))526527 def visit_Block(self, node, frame):528 """Call a block and register it for the template."""529 level = 1
2 unmodified lines
532 # check if we are one533 if self.has_known_extends:534 return535 if self.extends_so_far > 0:540 self.writeline('if parent_root is None:')536 self.writeline('if parent_template is None:')537 self.indent()538 level += 1539 self.writeline('for event in context.blocks[%r][-1](context):' % node.name)540 self.indent()
19 unmodified lines
560 # error into the generated code. We could catch that at compile561 # time too, but i welcome it not to confuse users by throwing the562 # same error at different times just "because we can".563 if not self.has_known_extends:568 self.writeline('if parent_root is not None:')564 self.writeline('if parent_template is not None:')565 self.indent()566 self.writeline('raise TemplateRuntimeError(%r)' %567 'extended multiple times')568
2 unmodified lines
571 if self.has_known_extends:572 raise CompilerExit()573 self.outdent()574579 self.writeline('parent_root = environment.get_template(', node, 1)575 self.writeline('parent_template = environment.get_template(', node, 1)576 self.visit(node.template, frame)581 self.write(', %r).root_render_func' % self.name)577 self.write(', %r)' % self.name)578 self.writeline('for name, parent_block in parent_template.'579 'blocks.iteritems():')580 self.indent()581 self.writeline('context.blocks.setdefault(name, []).'582 'insert(0, parent_block)')583 self.outdent()584585 # if this extends statement was in the root level we can take586 # advantage of that information and simplify the generated code587 # in the top level from this point onwards
14 unmodified lines
602 self.visit(node.template, frame)603 self.write(')')604 return605604 self.writeline('included_stream = environment.get_template(', node)606 self.writeline('included_template = environment.get_template(', node)607 self.visit(node.template, frame)606 self.write(').root_render_func(context, standalone=True)')607 self.writeline('included_context = included_stream.next()')608 self.writeline('for event in included_stream:')608 self.write(')')609 if frame.toplevel:610 self.writeline('included_context = included_template.new_context('611 'context.get_root())')612 self.writeline('for event in included_template.root_render_func('613 'included_context):')614 else:615 self.writeline('for event in included_template.root_render_func('616 'included_template.new_context(context.get_root())):')617 self.indent()618 if frame.buffer is None:619 self.writeline('yield event')620 else:
182 unmodified lines
803 # statement we have to add a check that disables our yield(s) here804 # so that they don't appear in the output.805 outdent_later = False806 if frame.toplevel and self.extends_so_far != 0:799 self.writeline('if parent_root is None:')807 self.writeline('if parent_template is None:')808 self.indent()809 outdent_later = True810811 # try to evaluate as many chunks as possible into a static
255 unmodified lines
modified:jinja2/debug.py+5 added-1 removed
36 unmodified lines
37 exc_type, exc_value, tb = exc_info3839 # figure the real context out40 real_locals = tb.tb_frame.f_locals.copy()41 locals = dict(real_locals.get('context', {}))41 ctx = real_locals.get('context')42 if ctx:43 locals = ctx.get_all()44 else:45 locals = {}46 for name, value in real_locals.iteritems():47 if name.startswith('l_'):48 locals[name[2:]] = value49
100 unmodified lines
modified:jinja2/environment.py+147 added-48 removed
11 unmodified lines
12from jinja2.lexer import Lexer13from jinja2.parser import Parser14from jinja2.optimizer import optimize15from jinja2.compiler import generate16from jinja2.runtime import Undefined16from jinja2.runtime import Undefined, TemplateContext17from jinja2.debug import translate_exception18from jinja2.utils import import_string18from jinja2.utils import import_string, LRUCache19from jinja2.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE202122# for direct template usage we have up to ten living environments23_spontaneous_environments = LRUCache(10)242526def _get_spontaneous_environment(*args):27 """Return a new spontaneus environment. A spontaneus environment is an28 unnamed and unaccessable (in theory) environment that is used for29 template generated from a string and not from the file system.30 """31 try:32 env = _spontaneous_environments.get(args)33 except TypeError:34 return Environment(*args)35 if env is not None:36 return env37 _spontaneous_environments[args] = env = Environment(*args)38 return env394041def template_from_code(environment, code, globals, uptodate=None,42 template_class=None):43 """Generate a new template object from code. It's used in the44 template constructor and the loader `load` implementation.45 """46 t = object.__new__(template_class or environment.template_class)47 namespace = {48 'environment': environment,49 '__jinja_template__': t50 }51 exec code in namespace52 t.environment = environment53 t.name = namespace['name']54 t.filename = code.co_filename55 t.root_render_func = namespace['root']56 t.blocks = namespace['blocks']57 t.globals = globals5859 # debug and loader helpers60 t._debug_info = namespace['debug_info']61 t._uptodate = uptodate6263 return t646566class Environment(object):67 """The Jinja environment.6869 The core component of Jinja is the `Environment`. It contains
66 unmodified lines
136 self.comment_start_string = comment_start_string137 self.comment_end_string = comment_end_string138 self.line_statement_prefix = line_statement_prefix139 self.trim_blocks = trim_blocks140141 # load extensions142 self.extensions = []143 for extension in extensions:144 if isinstance(extension, basestring):145 extension = import_string(extension)146 # extensions are instanciated early but initalized later.100 self.extensions.append(extension(self))147 self.extensions.append(object.__new__(extension))148149 # runtime information150 self.undefined = undefined151 self.optimized = optimized
2 unmodified lines
154 # defaults155 self.filters = DEFAULT_FILTERS.copy()156 self.tests = DEFAULT_TESTS.copy()157 self.globals = DEFAULT_NAMESPACE.copy()111 for extension in self.extensions:112 extension.update_globals(self.globals)158159 # set the loader provided160 self.loader = loader161162 # create lexer163 self.lexer = Lexer(self)164165 # initialize extensions166 for extension in self.extensions:167 extension.__init__(self)168169 def subscribe(self, obj, argument):170 """Get an item or attribute of an object."""171 try:172 return getattr(obj, str(argument))
55 unmodified lines
228 name = self.join_path(name, parent)229 globals = self.make_globals(globals)230 return self.loader.load(self, name, globals)231183 def from_string(self, source, globals=None):232 def from_string(self, source, globals=None, template_class=None):233 """Load a template from a string."""234 globals = self.make_globals(globals)186 return Template(self, self.compile(source, globals=globals),187 globals)235 return template_from_code(self, self.compile(source, globals=globals),236 globals, template_class)237238 def make_globals(self, d):239 """Return a dict for the globals."""240 if d is None:
1 unmodified line
242 return dict(self.globals, **d)243244245class Template(object):197 """Represents a template."""246 """The central template object. This class represents a compiled template247 and is used to evaluate it.248199 def __init__(self, environment, code, globals, uptodate=None):200 namespace = {201 'environment': environment,202 '__jinja_template__': self203 }204 exec code in namespace205 self.environment = environment206 self.name = namespace['name']207 self.filename = code.co_filename208 self.root_render_func = namespace['root']209 self.blocks = namespace['blocks']210 self.globals = globals249 Normally the template object is generated from an `Environment` but it250 also has a constructor that makes it possible to create a template251 instance directly using the constructor. It takes the same arguments as252 the environment constructor but it's not possible to specify a loader.253212 # debug and loader helpers213 self._get_debug_info = namespace['get_debug_info']214 self._uptodate = uptodate254 Every template object has a few methods and members that are guaranteed255 to exist. However it's important that a template object should be256 considered immutable. Modifications on the object are not supported.257258 Template objects created from the constructor rather than an environment259 do have an `environment` attribute that points to a temporary environment260 that is probably shared with other templates created with the constructor261 and compatible settings.262263 >>> template = Template('Hello {{ name }}!')264 >>> template.render(name='John Doe')265 u'Hello John Doe!'266267 >>> stream = template.stream(name='John Doe')268 >>> stream.next()269 u'Hello John Doe!'270 >>> stream.next()271 Traceback (most recent call last):272 ...273 StopIteration274 """275276 def __new__(cls, source,277 block_start_string='{%',278 block_end_string='%}',279 variable_start_string='{{',280 variable_end_string='}}',281 comment_start_string='{#',282 comment_end_string='#}',283 line_statement_prefix=None,284 trim_blocks=False,285 optimized=True,286 undefined=Undefined,287 extensions=(),288 finalize=unicode):289 # make sure extensions are hashable290 extensions = tuple(extensions)291 env = _get_spontaneous_environment(292 block_start_string, block_end_string, variable_start_string,293 variable_end_string, comment_start_string, comment_end_string,294 line_statement_prefix, trim_blocks, optimized, undefined,295 None, extensions, finalize)296 return env.from_string(source, template_class=cls)297298 def render(self, *args, **kwargs):299 """Render the template into a string."""300 try:301 return u''.join(self.generate(*args, **kwargs))
28 unmodified lines
330 'override%s global variable%s. '331 'With an enabled optimizer this '332 'will lead to unexpected results.' %333 (plural, ', '.join(overrides), plural or ' a', plural))252 gen = self.root_render_func(dict(self.globals, **context))253 # skip the first item which is a reference to the context254 gen.next()334335 try:257 for event in gen:336 for event in self.root_render_func(self.new_context(context)):337 yield event338 except:260 exc_info = translate_exception(sys.exc_info())261 raise exc_info[0], exc_info[1], exc_info[2]339 exc_type, exc_value, tb = translate_exception(sys.exc_info())340 raise exc_type, exc_value, tb341342 def new_context(self, vars):343 """Create a new template context for this template."""344 return TemplateContext(self.environment, dict(self.globals, **vars),345 self.name, self.blocks)346347 def get_corresponding_lineno(self, lineno):348 """Return the source line number of a line number in the349 generated bytecode as they are not in sync.350 """267 for template_line, code_line in reversed(self._get_debug_info()):351 for template_line, code_line in reversed(self.debug_info):352 if code_line <= lineno:353 return template_line354 return 1355356 @property357 def is_up_to_date(self):274 """Check if the template is still up to date."""358 """If this variable is `False` there is a newer version available."""359 if self._uptodate is None:360 return True361 return self._uptodate()362363 @property364 def debug_info(self):365 """The debug info mapping."""366 return [tuple(map(int, x.split('='))) for x in367 self._debug_info.split('&')]368369 def __repr__(self):370 return '<%s %r>' % (371 self.__class__.__name__,282 self.name372 self.name or '<from string>'373 )374375376class TemplateStream(object):287 """Wraps a genererator for outputing template streams."""377 """This class wraps a generator returned from `Template.generate` so that378 it's possible to buffer multiple elements so that it's possible to return379 them from a WSGI application which flushes after each iteration.380 """381382 def __init__(self, gen):383 self._gen = gen384 self._next = gen.next
7 unmodified lines
392 def enable_buffering(self, size=5):393 """Enable buffering. Buffer `size` items before yielding them."""394 if size <= 1:395 raise ValueError('buffer size too small')303 self.buffered = True396305 def buffering_next():397 def generator():398 buf = []399 c_size = 0400 push = buf.append401 next = self._gen.next402311 try:312 while 1:313 item = next()314 if item:315 push(item)403 while 1:404 try:405 while 1:406 push(next())407 c_size += 1317 if c_size >= size:318 raise StopIteration()319 except StopIteration:320 if not c_size:321 raise322 return u''.join(buf)408 if c_size >= size:409 raise StopIteration()410 except StopIteration:411 if not c_size:412 raise413 yield u''.join(buf)414 del buf[:]415 c_size = 0416324 self._next = buffering_next417 self.buffered = True418 self._next = generator().next419420 def __iter__(self):421 return self422423 def next(self):424 return self._next()425426427# hook in default template class. if anyone reads this comment: ignore that428# it's possible to use custom templates ;-)429Environment.template_class = Template
modified:jinja2/ext.py+7 added-4 removed
23 unmodified lines
2425 def __init__(self, environment):26 self.environment = environment2728 def update_globals(self, globals):29 """Called to inject runtime variables into the globals."""30 pass3128 def parse(self, parser):29 """Called if one of the tags matched."""303132class CacheExtension(Extension):33 """An example extension that adds cacheable blocks."""34 tags = set(['cache'])3536 def __init__(self, environment):37 Extension.__init__(self, environment)38 def dummy_cache_support(name, timeout=None, caller=None):39 if caller is not None:40 return caller()41 environment.globals['cache_support'] = dummy_cache_support4243 def parse(self, parser):44 lineno = parser.stream.next().lineno45 args = [parser.parse_expression()]46 if parser.stream.current.type is 'comma':
7 unmodified lines
modified:jinja2/i18n.py+3 added-3 removed
95 unmodified lines
9697class TransExtension(Extension):98 tags = set(['trans'])99100 def update_globals(self, globals):101 """Inject noop translation functions."""102 globals.update({100 def __init__(self, environment):101 Extension.__init__(self, environment)102 environment.globals.update({103 '_': lambda x: x,104 'gettext': lambda x: x,105 'ngettext': lambda s, p, n: (s, p)[n != 1]106 })
140 unmodified lines
modified:jinja2/lexer.py+8 added-8 removed
186 unmodified lines
187 the same configuration in a weak value dictionary.188 """189190 def __call__(cls, environment):191 key = hash((environment.block_start_string,192 environment.block_end_string,193 environment.variable_start_string,194 environment.variable_end_string,195 environment.comment_start_string,196 environment.comment_end_string,197 environment.line_statement_prefix,198 environment.trim_blocks))191 key = (environment.block_start_string,192 environment.block_end_string,193 environment.variable_start_string,194 environment.variable_end_string,195 environment.comment_start_string,196 environment.comment_end_string,197 environment.line_statement_prefix,198 environment.trim_blocks)199200 # use the cached lexer if possible201 if key in _lexer_cache:202 return _lexer_cache[key]
299 unmodified lines
modified:jinja2/loaders.py+63 added-4 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11from os import path12from jinja2.exceptions import TemplateNotFound13from jinja2.environment import Template13from jinja2.environment import template_from_code14from jinja2.utils import LRUCache151617def split_template_path(template):
11 unmodified lines
29 return pieces303132class BaseLoader(object):33 """34 Baseclass for all loaders. Subclass this and override `get_source` to33 """Baseclass for all loaders. Subclass this and override `get_source` to34 implement a custom loading mechanism.3536 The environment provides a `get_template` method that will automatically37 call the loader bound to an environment.
42 unmodified lines
80 return template8182 source, filename, uptodate = self.get_source(environment, name)83 code = environment.compile(source, name, filename, globals)85 template = Template(environment, code, globals, uptodate)84 template = template_from_code(environment, code, globals, uptodate)85 if self.cache is not None:86 self.cache[name] = template87 return template88
53 unmodified lines
142 def get_source(self, environment, template):143 if template in self.mapping:144 return self.mapping[template], None, None145 raise TemplateNotFound(template)146147148class FunctionLoader(BaseLoader):149 """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.153 """154155 def __init__(self, load_func, cache_size=50, auto_reload=True):156 BaseLoader.__init__(self, cache_size, auto_reload)157 self.load_func = load_func158159 def get_source(self, environment, template):160 rv = self.load_func(environment, template)161 if rv is None:162 raise TemplateNotFound(template)163 return rv164165166class PrefixLoader(BaseLoader):167 """A loader that is passed a dict of loaders where each loader is bound168 to a prefix. The caching is independent of the actual loaders so the169 per loader cache settings are ignored. The prefix is delimited from the170 template by a slash.171 """172173 def __init__(self, mapping, delimiter='/', cache_size=50,174 auto_reload=True):175 BaseLoader.__init__(self, cache_size, auto_reload)176 self.mapping = mapping177 self.delimiter = delimiter178179 def get_source(self, environment, template):180 try:181 prefix, template = template.split(self.delimiter, 1)182 loader = self.mapping[prefix]183 except (ValueError, KeyError):184 raise TemplateNotFound(template)185 return loader.get_source(environment, template)186187188class ChoiceLoader(BaseLoader):189 """This loader works like the `PrefixLoader` just that no prefix is190 specified. If a template could not be found by one loader the next one191 is tried. Like for the `PrefixLoader` the cache settings of the actual192 loaders don't matter as the choice loader does the caching.193 """194195 def __init__(self, loaders, cache_size=50, auto_reload=True):196 BaseLoader.__init__(self, cache_size, auto_reload)197 self.loaders = loaders198199 def get_source(self, environment, template):200 for loader in self.loaders:201 try:202 return loader.get_source(environment, template)203 except TemplateNotFound:204 pass205 raise TemplateNotFound(template)
modified:jinja2/nodes.py+6 added-4 removed
450 unmodified lines
451 def as_const(self):452 obj = self.node.as_const()453454 # don't evaluate context functions455 if type(obj) is FunctionType and \456 getattr(obj, 'contextfunction', False):457 raise Impossible()458455 args = [x.as_const() for x in self.args]456 if type(obj) is FunctionType:457 if getattr(obj, 'contextfunction', False):458 raise Impossible()459 elif obj.environmentfunction:460 args.insert(0, self.environment)461462 kwargs = dict(x.as_const() for x in self.kwargs)463 if self.dyn_args is not None:464 try:465 args.extend(self.dyn_args.as_const())
131 unmodified lines
modified:jinja2/runtime.py+80 added-70 removed
6 unmodified lines
78 :copyright: Copyright 2008 by Armin Ronacher.9 :license: GNU GPL.10"""11try:12 from collections import defaultdict13except ImportError:14 defaultdict = None11from types import FunctionType12from jinja2.utils import Markup, partial13from jinja2.exceptions import UndefinedError14
1 unmodified line
16__all__ = ['LoopContext', 'StaticLoopContext', 'TemplateContext',17 'Macro', 'IncludedTemplate', 'Markup']181924class TemplateContext(dict):20class TemplateContext(object):21 """Holds the variables of the local template or of the global one. It's22 not save to use this class outside of the compiled code. For example23 update and other methods will not work as they seem (they don't update24 the exported variables for example).25 """2631 def __init__(self, environment, globals, name, blocks, standalone):32 dict.__init__(self, globals)27 def __init__(self, environment, parent, name, blocks):28 self.parent = parent29 self.vars = {}30 self.environment = environment34 self.exported = set()31 self.exported_vars = set()32 self.name = name36 self.blocks = dict((k, [v]) for k, v in blocks.iteritems())3338 # give all context functions the context as first argument39 for key, value in self.iteritems():40 if type(value) is FunctionType and \41 getattr(value, 'contextfunction', False):42 dict.__setitem__(self, key, partial(value, self))34 # bind functions to the context of environment if required35 for name, obj in self.parent.iteritems():36 if type(obj) is FunctionType:37 if getattr(obj, 'contextfunction', 0):38 self.vars[key] = partial(obj, self)39 elif getattr(obj, 'environmentfunction', 0):40 self.vars[key] = partial(obj, environment)4144 # if the template is in standalone mode we don't copy the blocks over.45 # this is used for includes for example but otherwise, if the globals46 # are a template context, this template is participating in a template47 # inheritance chain and we have to copy the blocks over.48 if not standalone and isinstance(globals, TemplateContext):49 for name, parent_blocks in globals.blocks.iteritems():50 self.blocks.setdefault(name, []).extend(parent_blocks)42 # create the initial mapping of blocks. Whenever template inheritance43 # takes place the runtime will update this mapping with the new blocks44 # from the template.45 self.blocks = dict((k, [v]) for k, v in blocks.iteritems())4652 def super(self, block):47 def super(self, name, current):48 """Render a parent block."""54 try:55 func = self.blocks[block][-2]56 except LookupError:49 last = None50 for block in self.blocks[name]:51 if block is current:52 break53 last = block54 if last is None:55 return self.environment.undefined('there is no parent block '56 'called %r.' % block)59 return SuperBlock(block, self, func)57 return SuperBlock(block, self, last)5861 def __setitem__(self, key, value):62 """If we set items to the dict we track the variables set so63 that includes can access the exported variables."""64 dict.__setitem__(self, key, value)65 self.exported.add(key)59 def update(self, mapping):60 """Update vars from a mapping but don't export them."""61 self.vars.update(mapping)6263 def get_exported(self):68 """Get a dict of all exported variables."""69 return dict((k, self[k]) for k in self.exported)64 """Get a new dict with the exported variables."""65 return dict((k, self.vars[k]) for k in self.exported_vars)6671 # if there is a default dict, dict has a __missing__ method we can use.72 if defaultdict is None:73 def __getitem__(self, name):74 if name in self:75 return self[name]76 return self.environment.undefined(name=name)77 else:78 def __missing__(self, name):79 return self.environment.undefined(name=name)67 def get_root(self):68 """Return a new dict with all the non local variables."""69 return dict(self.parent)7071 def get_all(self):72 """Return a copy of the complete context as dict."""73 return dict(self.parent, **self.vars)7475 def __setitem__(self, key, value):76 self.vars[key] = value77 self.exported_vars.add(key)7879 def __getitem__(self, key):80 if key in self.vars:81 return self.vars[key]82 try:83 return self.parent[key]84 except KeyError:85 return self.environment.undefined(name=key)8687 def __repr__(self):88 return '<%s %s of %r>' % (89 self.__class__.__name__,90 dict.__repr__(self),
23 unmodified lines
114 """Represents an included template."""115116 def __init__(self, environment, context, template):117 template = environment.get_template(template)112 gen = template.root_render_func(context, standalone=True)113 context = gen.next()118 context = template.new_context(context.get_root())119 self._name = template.name115 self._rendered_body = u''.join(gen)120 self._rendered_body = u''.join(template.root_render_func(context))121 self._context = context.get_exported()122123 __getitem__ = lambda x, n: x._context[n]124 __html__ = __unicode__ = lambda x: x._rendered_body
136 unmodified lines
261 self.name is None and 'anonymous' or repr(self.name)262 )263264265def fail_with_undefined_error(self, *args, **kwargs):266 """Regular callback function for undefined objects that raises an267 `UndefinedError` on call.268 """269 if self._undefined_hint is None:270 if self._undefined_obj is None:271 hint = '%r is undefined' % self._undefined_name272 elif not isinstance(self._undefined_name, basestring):273 hint = '%r object has no element %r' % (274 self._undefined_obj.__class__.__name__,275 self._undefined_name276 )277 else:278 hint = '%r object has no attribute %r' % (279 self._undefined_obj.__class__.__name__,280 self._undefined_name281 )282 else:283 hint = self._undefined_hint284 raise UndefinedError(hint)285286287class Undefined(object):288 """The default undefined implementation. This undefined implementation289 can be printed and iterated over, but every other access will raise a290 `NameError`. Custom undefined classes must subclass this.
3 unmodified lines
294 self._undefined_hint = hint295 self._undefined_obj = obj296 self._undefined_name = name297271 def _fail_with_error(self, *args, **kwargs):272 if self._undefined_hint is None:273 if self._undefined_obj is None:274 hint = '%r is undefined' % self._undefined_name275 elif not isinstance(self._undefined_name, basestring):276 hint = '%r object has no element %r' % (277 self._undefined_obj.__class__.__name__,278 self._undefined_name279 )280 else:281 hint = '%r object has no attribute %r' % (282 self._undefined_obj.__class__.__name__,283 self._undefined_name284 )285 else:286 hint = self._undefined_hint287 raise UndefinedError(hint)298 __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \299 __realdiv__ = __rrealdiv__ = __floordiv__ = __rfloordiv__ = \300 __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \291 __getattr__ = __getitem__ = _fail_with_error301 __getattr__ = __getitem__ = fail_with_undefined_error302293 def __unicode__(self):294 return u''295303 def __str__(self):304 return self.__unicode__().encode('utf-8')305306 def __repr__(self):307 return 'Undefined'308309 def __unicode__(self):310 return u''311312 def __len__(self):313 return 0314315 def __iter__(self):
18 unmodified lines
334 return u'{{ undefined value printed: %s }}' % self._undefined_hint335336337class StrictUndefined(Undefined):328 """An undefined that barks on print and iteration as well as boolean tests.329 In other words: you can do nothing with it except checking if it's defined330 using the `defined` test.338 """An undefined that barks on print and iteration as well as boolean339 tests. In other words: you can do nothing with it except checking if it's340 defined using the `defined` test.341 """342333 __iter__ = __unicode__ = __len__ = __nonzero__ = Undefined._fail_with_error343 __iter__ = __unicode__ = __len__ = __nonzero__ = fail_with_undefined_error
modified:jinja2/utils.py+8 added
31 unmodified lines
32 f.contextfunction = True33 return f343536def environmentfunction(f):37 """Mark a callable as environment callable. An environment callable is38 passed the current environment as first argument.39 """40 f.environmentfunction = True41 return f424344def import_string(import_name, silent=False):45 """Imports an object based on a string. This use useful if you want to46 use import paths as endpoints or something similar. An import path can47 be specified either in dotted notation (``xml.sax.saxutils.escape``)
374 unmodified lines
modified:tests/test_syntax.py+4 added-31 removed
20 unmodified lines
21UNARY = '''{{ +3 }}|{{ -3 }}'''22CONCAT = '''{{ [1, 2] ~ 'foo' }}'''23COMPARE = '''{{ 1 > 0 }}|{{ 1 >= 1 }}|{{ 2 < 3 }}|{{ 2 == 2 }}|{{ 1 <= 1 }}'''24INOP = '''{{ 1 in [1, 2, 3] }}|{{ 1 not in [1, 2, 3] }}'''25LITERALS = '''{{ [] }}|{{ {} }}|{{ () }}|{{ '' }}|{{ @() }}'''25LITERALS = '''{{ [] }}|{{ {} }}|{{ () }}'''26BOOL = '''{{ true and false }}|{{ false or true }}|{{ not false }}'''27GROUPING = '''{{ (true and false) or (false and true) and not false }}'''28CONDEXPR = '''{{ 0 if true else 1 }}'''29DJANGOATTR = '''{{ [1, 2, 3].0 }}'''30FILTERPRIORITY = '''{{ "foo"|upper + "bar"|upper }}'''31REGEX = r'''{{ @/\S+/.findall('foo bar baz') }}'''31TUPLETEMPLATES = [32 '{{ () }}',33 '{{ (1, 2) }}',34 '{{ (1, 2,) }}',
5 unmodified lines
40 '{% for x in foo, recursive %}...{% endfor %}',41 '{% for x in foo, bar recursive %}...{% endfor %}',42 '{% for x, in foo, recursive %}...{% endfor %}'43]45TRAILINGCOMMA = '''{{ (1, 2,) }}|{{ [1, 2,] }}|{{ {1: 2,} }}|{{ @(1, 2,) }}'''44TRAILINGCOMMA = '''{{ (1, 2,) }}|{{ [1, 2,] }}|{{ {1: 2,} }}'''454647def test_call():48 from jinja2 import Environment
59 unmodified lines
108109110def test_literals(env):111 tmpl = env.from_string(LITERALS)113 assert tmpl.render().lower() == '[]|{}|()||set([])'112 assert tmpl.render().lower() == '[]|{}|()'113114115def test_bool(env):116 tmpl = env.from_string(BOOL)
43 unmodified lines
160 else:161 env.from_string('foo(%s)' % sig)162163165def test_regex(env):166 tmpl = env.from_string(REGEX)167 assert tmpl.render() == "['foo', 'bar', 'baz']"168169164def test_tuple_expr(env):165 for tmpl in TUPLETEMPLATES:166 assert env.from_string(tmpl)167168169def test_trailing_comma(env):170 tmpl = env.from_string(TRAILINGCOMMA)177 assert tmpl.render().lower() == '(1, 2)|[1, 2]|{1: 2}|set([1, 2])'178179180def test_extends_position():181 env = Environment(loader=DictLoader({182 'empty': '[{% block empty %}{% endblock %}]'183 }))184 tests = [185 ('{% extends "empty" %}', '[!]'),186 (' {% extends "empty" %}', '[!]'),187 (' !\n', ' !\n!'),188 ('{# foo #} {% extends "empty" %}', '[!]'),189 ('{% set foo = "blub" %}{% extends "empty" %}', None)190 ]191192 for tmpl, expected_output in tests:193 try:194 tmpl = env.from_string(tmpl + '{% block empty %}!{% endblock %}')195 except TemplateSyntaxError:196 assert expected_output is None, 'got syntax error'197 else:198 assert expected_output == tmpl.render()171 assert tmpl.render().lower() == '(1, 2)|[1, 2]|{1: 2}'
modified:setup.py+28 added-28 removed
1# -*- coding: utf-8 -*-2"""3jinja4~~~~~3Jinja24~~~~~~56Jinja is a `sandboxed`_ template engine written in pure Python. It7provides a `Django`_ like non-XML syntax and compiles templates into8executable python code. It's basically a combination of Django templates9and python code.6Jinja2 is a template engine written in pure Python. It provides a7`Django`_ inspired non-XML syntax but supports inline expressions and8an optional `sandboxed`_ environment.910Nutshell11--------12
3 unmodified lines
16 {% block title %}Memberlist{% endblock %}17 {% block content %}18 <ul>19 {% for user in users %}21 <li><a href="{{ user.url|e }}">{{ user.username|e }}</a></li>20 <li><a href="{{ user.url }}">{{ user.username }}</a></li>21 {% endfor %}22 </ul>23 {% endblock %}24
2 unmodified lines
2728Application logic is for the controller but don't try to make the life29for the template designer too hard by giving him too few functionality.3032For more informations visit the new `jinja webpage`_ and `documentation`_.31For more informations visit the new `jinja2 webpage`_ and `documentation`_.3234Note35----33The `Jinja2 tip`_ is installable via `easy_install` with ``easy_install34Jinja2==dev``.3537This is the Jinja 1.0 release which is completely incompatible with the38old "pre 1.0" branch. The old branch will still receive security updates39and bugfixes but the 1.0 branch will be the only version that receives40support.4142If you have an application that uses Jinja 0.9 and won't be updated in43the near future the best idea is to ship a Jinja 0.9 checkout together44with the application.4546The `Jinja tip`_ is installable via `easy_install` with ``easy_install47Jinja==dev``.4836.. _sandboxed: http://en.wikipedia.org/wiki/Sandbox_(computer_security)37.. _Django: http://www.djangoproject.com/51.. _jinja webpage: http://jinja.pocoo.org/52.. _documentation: http://jinja.pocoo.org/documentation/index.html53.. _Jinja tip: http://dev.pocoo.org/hg/jinja-main/archive/tip.tar.gz#egg=Jinja-dev38.. _jinja webpage: http://jinja2.pocoo.org/39.. _documentation: http://jinja2.pocoo.org/documentation/index.html40.. _Jinja tip: http://dev.pocoo.org/hg/jinja2-main/archive/tip.tar.gz#egg=Jinja2-dev41"""42import os43import sys44import ez_setup
12 unmodified lines
57 if os.path.isfile(fn):58 yield fn596061def get_terminal_width():62 """Return the current terminal dimensions."""63 try:64 from struct import pack, unpack65 from fcntl import ioctl66 from termios import TIOCGWINSZ67 s = pack('HHHH', 0, 0, 0, 0)68 return unpack('HHHH', ioctl(sys.stdout.fileno(), TIOCGWINSZ, s))[1]69 except:70 return 80717273class optional_build_ext(build_ext):74 """This class allows C extension building to fail."""7576 def run(self):
8 unmodified lines
85 except CCompilerError, x:86 self._unavailable()8788 def _unavailable(self):89 width = get_terminal_width()90 print '*' * 7090 print '*' * width91 print """WARNING:92An optional C extension could not be compiled, speedups will not be93available."""94 print '*' * 7094 print '*' * width959697setup(98 name='Jinja 2',98 name='Jinja2',99 version='2.0dev',100 url='http://jinja.pocoo.org/',101 license='BSD',102 author='Armin Ronacher',
37 unmodified lines