[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
Provenance
- Commit
9baa5ba- Tree
4a8aa85- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
f859485
10 files changed+161 added−41 removed
modified:docs/src/designerdoc.txt+28 added
620 unmodified lines621 </html>622 {% endfilter %}623 {% endraw %}624 625+Reserved Keywords626+=================627+628+Jinja has some keywords you cannot use a variable names. This limitation629+exists to make look coherent. Syntax highlighters won't mess things up and630+you will don't have unexpected output.631+632+The following keywords exist and cannot be used as identifiers:633+634+ `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`638+639+If you want to use such a name you have to prefix or suffix it or use640+alternative names:641+642+.. sourcecode:: jinja643+644+ {% for macro_ in macros %}645+ {{ macro_('foo') }}646+ {% endfor %}647+648+If future Jinja releases add new keywords those will be "light" keywords which649+means that they won't raise an error for several releases but yield warnings650+on the application side. But it's very unlikely that new keywords will be651+added.652+653 Internationalization654 ====================655 656 If the application is configured for i18n, you can define translatable blocks57 unmodified linesmodified:jinja/translators/python.py+1 added-1 removed
573 unmodified lines574 575 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 linesmodified:jinja/lexer.py+9 added-9 removed
32 unmodified lines33 '.', ':', ',', '|', '==', '<', '>', '<=', '>=', '!=', '=',34 ur'or\b', ur'and\b', ur'not\b', ur'in\b', ur'is'35 ]))36 37-# set of names that are keywords in python but not in jinja. the lexer38-# appends three trailing underscores, the parser removes them again later39-escaped_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 keywords38+keywords = 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'])43 44 45 class Failure(object):46 """73 unmodified lines120 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.123 124- 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())132 133 def tokeniter(self, source):100 unmodified linesmodified:jinja/loaders.py+5 added-5 removed
173 unmodified lines174 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 lines264 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 -1269 270 271 class PackageLoader(CachedLoaderMixin, BaseLoader):272 """57 unmodified lines330 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 -1335 336 337 class FunctionLoader(CachedLoaderMixin, BaseLoader):338 """23 unmodified lines362 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't100 unmodified linesmodified:jinja/nodes.py+5 added-7 removed
1 unmodified line2 """3 jinja.nodes4 ~~~~~~~~~~~5 6- Additional nodes for jinja. Look like nodes from the ast.6+ Additional nodes for Jinja. Look like nodes from the ast.7 8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """27 unmodified lines38 39 40 class Node(ast.Node):41 """42- jinja node.42+ Jinja node.43 """44 45 def get_items(self):46 return []48 unmodified lines95 self.extends = extends96 self.filename = filename97 98 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 []100 101 def __repr__(self):102 return 'Template(%r, %r, %r)' % (103 self.filename,141 unmodified lines245 self.body = body246 self.filters = filters247 248 def get_items(self):251- return [self.body, self.filters]249+ return [self.body] + list(self.filters)250 251 def __repr__(self):254- return 'Filter(%r)' % (252+ return 'Filter(%r, %r)' % (253 self.body,254 self.filters255 )256 86 unmodified linesmodified:jinja/parser.py+74 added-15 removed
10 unmodified lines11 import re12 from compiler import ast, parse13 from compiler.misc import set_filename14 from jinja import nodes15-from jinja.lexer import escaped_names15 from jinja.datastructure import TokenStream16 from jinja.exceptions import TemplateSyntaxError17 try:18 set95 unmodified lines114 else:115 else_ = None116 self.close_remaining_block()117 119- 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))120 121 def handle_if_directive(self, lineno, gen):122 """123 Handle if/else blocks.38 unmodified lines162 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)172 173 def handle_filter_directive(self, lineno, gen):174 """175 Handle {% filter foo|bar %} directives.28 unmodified lines204 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)213+203- 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()218 219 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 lines243 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)256 257 # 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)262 263 # 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)267 268 def handle_extends_directive(self, lineno, gen):269 """270 Handle the extends directive used for inheritance.52 unmodified lines323 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.expr336 337 # look for endtrans/pluralize338 buf = singular = []339 plural = indicator = None5 unmodified lines345 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 lines382 _, 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 lines452 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 linesmodified:jinja/plugin.py+18 added-3 removed
9 unmodified lines10 :copyright: 2007 by Armin Ronacher.11 :license: BSD, see LICENSE for more details.12 """13 from jinja.environment import Environment14-from jinja.loaders import FunctionLoader14+from jinja.loaders import FunctionLoader, FileSystemLoader, PackageLoader15 from jinja.exceptions import TemplateNotFound16 17 18 def jinja_plugin_factory(options):10 unmodified lines29 =================== =================================================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 lines73 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 lines96 try:97 tmpl = env.get_template(template)98 except TemplateNotFound:99 return85- return (tmpl.render(**values),)100+ return tmpl.render(**values)101 102 return render_functionmodified:tests/test_loaders.py+14 added
17 unmodified lines18 package_loader = loaders.PackageLoader('loaderres', 'templates')19 20 filesystem_loader = loaders.FileSystemLoader('loaderres/templates')21 22+function_loader = loaders.FunctionLoader({'justfunction.html': 'FOO'}.get)23+24 choice_loader = loaders.ChoiceLoader([dict_loader, package_loader])25 26 27 def test_dict_loader():43 unmodified lines71 except TemplateNotFound:72 pass73 else:74 raise AssertionError('expected template exception')75+76+77+def 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 lines9 #10 11 test:12 @(cd tests; py.test $(TESTS))13+14+documentation:15+ @(cd docs; ./generate.py)16+17+webpage:18+ @(cd www; ./generate.py)modified:setup.py+1 added-1 removed
28 unmodified lines29 '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 )