Skip to content
Myr

[svn] again huge jinja update. this time regarding keywords

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 f859485 · Browse files · 10 files+161 added−41 removed
This commit

State

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

Diff stats

10 files+161 added−41 removed

  • tests:+14 added−0 removed
  • other:+147 added−41 removed

10 files+161 added−41 removed

modified:docs/src/designerdoc.txt+28 added
620 unmodified lines
621 </html>622 {% endfilter %}623 {% endraw %}624625Reserved Keywords626=================627628Jinja has some keywords you cannot use a variable names. This limitation629exists to make look coherent. Syntax highlighters won't mess things up and630you will don't have unexpected output.631632The following keywords exist and cannot be used as identifiers:633634 `and`, `block`, `cycle`, `elif`, `else`, `endblock`, `endfilter`,635 `endfor`, `endif`, `endmacro`, `endraw`, `endtrans`, `extends`, `filter`,636 `for`, `if`, `in`, `include`, `is`, `macro`, `not`, `or`, `pluralize`,637 `raw`, `recursive`, `set`, `trans`638639If you want to use such a name you have to prefix or suffix it or use640alternative names:641642.. sourcecode:: jinja643644 {% for macro_ in macros %}645 {{ macro_('foo') }}646 {% endfor %}647648If future Jinja releases add new keywords those will be "light" keywords which649means that they won't raise an error for several releases but yield warnings650on the application side. But it's very unlikely that new keywords will be651added.652653Internationalization654====================655656If the application is configured for i18n, you can define translatable blocks
57 unmodified lines
modified:jinja/translators/python.py+1 added-1 removed
573 unmodified lines
574575 write('ctx_push()')576 nodeinfo = self.nodeinfo(node.body)577 if nodeinfo:578 write(nodebody)578 write(nodeinfo)579 buf.append(self.handle_node(node.body))580 write('ctx_pop()')581 return '\n'.join(buf)582
313 unmodified lines
modified:jinja/lexer.py+9 added-9 removed
32 unmodified lines
33 '.', ':', ',', '|', '==', '<', '>', '<=', '>=', '!=', '=',34 ur'or\b', ur'and\b', ur'not\b', ur'in\b', ur'is'35]))3637# set of names that are keywords in python but not in jinja. the lexer38# appends three trailing underscores, the parser removes them again later39escaped_names = set(['with', 'as', 'import', 'from', 'class', 'def',40 'try', 'except', 'exec', 'global', 'assert',41 'break', 'continue', 'lambda', 'return', 'raise',42 'yield', 'while', 'pass', 'finally'])37# set of used keywords38keywords = set(['and', 'block', 'cycle', 'elif', 'else', 'endblock',39 'endfilter', 'endfor', 'endif', 'endmacro', 'endraw',40 'endtrans', 'extends', 'filter', 'for', 'if', 'in',41 'include', 'is', 'macro', 'not', 'or', 'pluralize', 'raw',42 'recursive', 'set', 'trans'])434445class Failure(object):46 """
73 unmodified lines
120 tuples. Wrap the generator returned by this function in a121 `TokenStream` to get real token instances and be able to push tokens122 back to the stream. That's for example done by the parser.123124 Additionally some names like "class" are escaped124 Additionally non keywords are escaped.125 """126 def filter():127 for lineno, token, value in self.tokeniter(source):128 if token == 'name' and value in escaped_names:129 value += '___'128 if token == 'name' and value not in keywords:129 value += '_'130 yield lineno, token, value131 return TokenStream(filter())132133 def tokeniter(self, source):
100 unmodified lines
modified:jinja/loaders.py+5 added-5 removed
173 unmodified lines
174 if tmpl is not None and last_change is None:175 try:176 cache_time = path.getmtime(cache_fn)177 except OSError:178 cache_time = 0179 if last_change >= cache_time:178 cache_time = -1179 if cache_time == -1 or last_change >= cache_time:180 f = file(cache_fn, 'rb')181 try:182 tmpl = Template.load(environment, f)183 finally:
80 unmodified lines
264 def check_source_changed(self, environment, name):265 filename = get_template_filename(self.searchpath, name)266 if path.exists(filename):267 return path.getmtime(filename)268 return 0268 return -1269270271class PackageLoader(CachedLoaderMixin, BaseLoader):272 """
57 unmodified lines
330 fn = resource_filename(self.package_name, '/'.join([self.package_path] +331 [p for p in name.split('/') if p and p[0] != '.']))332 if resource_exists(self.package_name, fn):333 return path.getmtime(fn)334 return 0334 return -1335336337class FunctionLoader(CachedLoaderMixin, BaseLoader):338 """
23 unmodified lines
362 it's used to load a template. If the return363 value is None it's considered missing.364 ``getmtime_func`` Function used to check if templates requires365 reloading. Has to return the UNIX timestamp of366 the last template change or 0 if this template366 the last template change or ``-1`` if this template367 does not exist or requires updates at any cost.368 ``use_memcache`` Set this to ``True`` to enable memory caching.369 This is usually a good idea in production mode,370 but disable it during development since it won't
100 unmodified lines
modified:jinja/nodes.py+5 added-7 removed
1 unmodified line
2"""3 jinja.nodes4 ~~~~~~~~~~~56 Additional nodes for jinja. Look like nodes from the ast.6 Additional nodes for Jinja. Look like nodes from the ast.78 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""
27 unmodified lines
383940class Node(ast.Node):41 """42 jinja node.42 Jinja node.43 """4445 def get_items(self):46 return []
48 unmodified lines
95 self.extends = extends96 self.filename = filename9798 def get_items(self):99 if self.extends is not None:100 return [self.extends]101 return []99 return self.extends is not None and [self.extends] or []100101 def __repr__(self):102 return 'Template(%r, %r, %r)' % (103 self.filename,
141 unmodified lines
245 self.body = body246 self.filters = filters247248 def get_items(self):251 return [self.body, self.filters]249 return [self.body] + list(self.filters)250251 def __repr__(self):254 return 'Filter(%r)' % (252 return 'Filter(%r, %r)' % (253 self.body,254 self.filters255 )256
86 unmodified lines
modified:jinja/parser.py+74 added-15 removed
10 unmodified lines
11import re12from compiler import ast, parse13from compiler.misc import set_filename14from jinja import nodes15from jinja.lexer import escaped_names15from jinja.datastructure import TokenStream16from jinja.exceptions import TemplateSyntaxError17try:18 set
95 unmodified lines
114 else:115 else_ = None116 self.close_remaining_block()117119 return nodes.ForLoop(lineno, ast.assign, ast.list, body, else_, bool(recursive))118 return nodes.ForLoop(lineno, ast.assign, ast.list, body, else_,119 bool(recursive))120121 def handle_if_directive(self, lineno, gen):122 """123 Handle if/else blocks.
38 unmodified lines
162 raise ValueError()163 except (StopIteration, ValueError):164 raise TemplateSyntaxError('invalid syntax for set', lineno)165 ast = self.parse_python(lineno, gen, '(%s)')166 # disallow keywords167 if not name[2].endswith('_'):168 raise TemplateSyntaxError('illegal use of keyword %r '169 'as identifier in set statement.' %170 name[2], lineno)166 return nodes.Set(lineno, str(name[2]), ast.expr)171 return nodes.Set(lineno, str(name[2][:-1]), ast.expr)172173 def handle_filter_directive(self, lineno, gen):174 """175 Handle {% filter foo|bar %} directives.
28 unmodified lines
204 raise TemplateSyntaxError('macro requires a name', lineno)205 if macro_name[1] != 'name':206 raise TemplateSyntaxError('expected \'name\', got %r' %207 macro_name[1], lineno)208 # disallow keywords as identifiers209 elif not macro_name[2].endswith('_'):210 raise TemplateSyntaxError('illegal use of keyword %r '211 'as macro name.' % macro_name[2],212 lineno)213203 ast = self.parse_python(lineno, gen, 'def %s(%%s):pass' % str(macro_name[2]))214 ast = self.parse_python(lineno, gen, 'def %s(%%s):pass' %215 str(macro_name[2][:-1]))216 body = self.subparse(end_of_macro, True)217 self.close_remaining_block()218219 if ast.varargs or ast.kwargs:220 raise TemplateSyntaxError('variable length macro signature '221 'not allowed.', lineno)222 if ast.argnames:223 defaults = [None] * (len(ast.argnames) - len(ast.defaults)) + ast.defaults212 args = zip(ast.argnames, defaults)224 args = []225 for idx, argname in enumerate(ast.argnames):226 # disallow keywords as argument names227 if not argname.endswith('_'):228 raise TemplateSyntaxError('illegal use of keyword %r '229 'as macro argument.' % argname,230 lineno)231 args.append((argname[:-1], defaults[idx]))232 else:233 args = None234 return nodes.Macro(lineno, ast.name, args, body)235
7 unmodified lines
243 block_name = tokens.pop(0)244 if block_name[1] != 'name':245 raise TemplateSyntaxError('expected \'name\', got %r' %246 block_name[1], lineno)247 # disallow keywords248 if not block_name[2].endswith('_'):249 raise TemplateSyntaxError('illegal use of keyword %r '250 'as block name.' % block_name[2],251 lineno)252 name = block_name[2][:-1]253 if tokens:254 raise TemplateSyntaxError('block got too many arguments, '255 'requires one.', lineno)256257 # check if this block does not exist by now.233 if block_name[2] in self.blocks:258 if name in self.blocks:259 raise TemplateSyntaxError('block %r defined twice' %235 block_name[2], lineno)236 self.blocks.add(block_name[2])260 name, lineno)261 self.blocks.add(name)262263 # now parse the body and attach it to the block264 body = self.subparse(end_of_block_tag, True)265 self.close_remaining_block()241 return nodes.Block(lineno, block_name[2], body)266 return nodes.Block(lineno, name, body)267268 def handle_extends_directive(self, lineno, gen):269 """270 Handle the extends directive used for inheritance.
52 unmodified lines
323 for arg in self.parse_python(lineno, gen, '_trans(%s)').expr.args:324 if arg.__class__ is not ast.Keyword:325 raise TemplateSyntaxError('translation tags need explicit '326 'names for values.', lineno)327 # argument name doesn't end with "_"? that's a keyword then328 if not arg.name.endswith('_'):329 raise TemplateSyntaxError('illegal use of keyword %r '330 'as identifier.' % arg.name,331 lineno)332 # remove the last "_" before writing333 if first_var is None:303 first_var = arg.name304 replacements[arg.name] = arg.expr334 first_var = arg.name[:-1]335 replacements[arg.name[:-1]] = arg.expr336337 # look for endtrans/pluralize338 buf = singular = []339 plural = indicator = None
5 unmodified lines
345 self.tokenstream.drop_until(end_of_comment, True)346 # nested variables347 elif token == 'variable_begin':348 _, variable_token, variable_name = self.tokenstream.next()318 if variable_token != 'name' or variable_name not in replacements:349 if variable_token != 'name':350 raise TemplateSyntaxError('can only use variable not '351 'constants or expressions '352 'in translation variable '353 'blocks.', lineno)354 # plural name without trailing "_"? that's a keyword355 if not variable_name.endswith('_'):356 raise TemplateSyntaxError('illegal use of keyword '357 '%r as identifier in trans '358 'block.' % variable_name, lineno)359 variable_name = variable_name[:-1]360 if variable_name not in replacements:361 raise TemplateSyntaxError('unregistered translation '362 'variable %r.' % variable_name,363 lineno)364 if self.tokenstream.next()[1] != 'variable_end':
17 unmodified lines
382 _, plural_token, plural_name = self.tokenstream.next()383 if plural_token == 'block_end':384 indicator = first_var385 elif plural_token == 'name':386 # plural name without trailing "_"? that's a keyword387 if not plural_name.endswith('_'):388 raise TemplateSyntaxError('illegal use of keyword '389 '%r as identifier.' %390 plural_name, lineno)391 plural_name = plural_name[:-1]392 if plural_name not in replacements:393 raise TemplateSyntaxError('unknown tranlsation '394 'variable %r' %395 plural_name, lineno)
56 unmodified lines
452 body = self.subparse(None)453 todo = [body]454 while todo:455 node = todo.pop()408 if node.__class__ in (ast.AssName, ast.Name) and \409 node.name.endswith('___') and node.name[:-3] in escaped_names:410 node.name = node.name[:-3]456 # all names excluding keywords have an trailing underline.457 # if we find a name without trailing underline that's a keyword458 # and this code raises an error. else strip the underline again459 if node.__class__ in (ast.AssName, ast.Name):460 if not node.name.endswith('_'):461 raise TemplateSyntaxError('illegal use of keyword %r '462 'as identifier.' % node.name,463 node.lineno)464 node.name = node.name[:-1]465 elif node.__class__ is ast.Getattr:466 if not node.attrname.endswith('_'):467 raise TemplateSyntaxError('illegal use of keyword %r '468 'as attribute name.' % node.name)469 node.attrname = node.attrname[:-1]470 node.filename = self.filename471 todo.extend(node.getChildNodes())472 return nodes.Template(self.filename, body, self.extends)473
94 unmodified lines
modified:jinja/plugin.py+18 added-3 removed
9 unmodified lines
10 :copyright: 2007 by Armin Ronacher.11 :license: BSD, see LICENSE for more details.12"""13from jinja.environment import Environment14from jinja.loaders import FunctionLoader14from jinja.loaders import FunctionLoader, FileSystemLoader, PackageLoader15from jinja.exceptions import TemplateNotFound161718def jinja_plugin_factory(options):
10 unmodified lines
29 =================== =================================================30 ``environment`` If this is provided it must be the only31 configuration value and it's used as jinja32 environment.33 ``searchpath`` If provided a new file system loader with this34 search path is instanciated.35 ``package`` Name of the python package containing the36 templates. If this and ``package_path`` is37 defined a `PackageLoader` is used.38 ``package_path`` Path to the templates inside of a package.39 ``loader_func`` Function that takes the name of the template to40 load. If it returns a string or unicode object41 it's used to load a template. If the return42 value is None it's considered missing.
30 unmodified lines
73 use_memcache = options.pop('use_memcache', False)74 memcache_size = options.pop('memcache_size', 40)75 cache_folder = options.pop('cache_folder', None)76 auto_reload = options.pop('auto_reload', True)77 if 'searchpath' in options:78 options['loader'] = FileSystemLoader(options.pop('searchpath'),79 use_memcache, memcache_size,80 cache_folder, auto_reload)81 elif 'package' in options:82 options['loader'] = PackageLoader(options.pop('package'),83 options.pop('package_path', ''),84 use_memcache, memcache_size,85 cache_folder, auto_reload)71 if loader_func is not None:86 elif loader_func is not None:87 options['loader'] = FunctionLoader(loader_func, getmtime_func,88 use_memcache, memcache_size,89 cache_folder, auto_reload)90 env = Environment(**options)
5 unmodified lines
96 try:97 tmpl = env.get_template(template)98 except TemplateNotFound:99 return85 return (tmpl.render(**values),)100 return tmpl.render(**values)101102 return render_function
modified:tests/test_loaders.py+14 added
17 unmodified lines
18package_loader = loaders.PackageLoader('loaderres', 'templates')1920filesystem_loader = loaders.FileSystemLoader('loaderres/templates')2122function_loader = loaders.FunctionLoader({'justfunction.html': 'FOO'}.get)2324choice_loader = loaders.ChoiceLoader([dict_loader, package_loader])252627def test_dict_loader():
43 unmodified lines
71 except TemplateNotFound:72 pass73 else:74 raise AssertionError('expected template exception')757677def test_function_loader():78 env = Environment(loader=function_loader)79 tmpl = env.get_template('justfunction.html')80 assert tmpl.render().strip() == 'FOO'81 try:82 env.get_template('missing.html')83 except TemplateNotFound:84 pass85 else:86 raise AssertionError('expected template exception')
modified:Makefile+6 added
8 unmodified lines
9#1011test:12 @(cd tests; py.test $(TESTS))1314documentation:15 @(cd docs; ./generate.py)1617webpage:18 @(cd www; ./generate.py)
modified:setup.py+1 added-1 removed
28 unmodified lines
29 'Topic :: Text Processing :: Markup :: HTML'30 ],31 keywords = ['python.templating.engines'],32 packages = ['jinja', 'jinja.translators'],33 extras_require = {'plugin': ['setuptools>=0.6a2']}33 extras_require = {'plugin': ['setuptools>=0.6a2']},34)