Skip to content
Myr

[svn] various updates i haven't checked in so far (see the diff of the changelog) and fixed critical bug reported by Alexey Melchakov

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 d459e27 · Browse files · 20 files+665 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

20 files+665 added−156 removed

  • tests:+106 added−2 removed
  • other:+559 added−154 removed

20 files+665 added−156 removed

modified:docs/src/contextenv.txt+17 added-6 removed
38 unmodified lines
3940 Get the translations for the template `name`. Only works if a loader41 is present. See the `i18n`_ section for more details.4243**def** `get_translations_for_string` *(self, string)*:4445 Get the translations for the string `string`. This works also if no46 loader is present and can be used to lookup translation strings from47 templates that are loaded from dynamic resources like databases.4849**def** `apply_filters` *(self, value, context, filters)*:5051 Now this function is a bit tricky and you usually don't have to override52 it. It's used to apply filters on a value. The Jinja expression
9 unmodified lines
62 `replace` is called with the two literal strings ``a`` and ``b``, both63 unicode. The filters for the names are stored on ``self.filters`` in a64 dict. Missing filters should raise a `FilterNotFound` exception.6560 **Warning** this is a jinja internal method. The actual implementation66 **Warning** this is a Jinja internal method. The actual implementation67 and function signature might change.6869**def** `perform_test` *(self, context, testname, args, value, invert)*:70
6 unmodified lines
77 with the `is not` operator, `False` if with the `is` operator.7879 Missing tests should raise a `TestNotFound` exception.8075 **Warning** this is a jinja internal method. The actual implementation81 **Warning** this is a Jinja internal method. The actual implementation82 and function signature might change.8384**def** `get_attribute` *(self, obj, attribute)*:8586 Get `attribute` from the object provided. The default implementation87 performs security tests.8883 **Warning** this is a jinja internal method. The actual implementation89 **Warning** this is a Jinja internal method. The actual implementation90 and function signature might change.9192**def** `get_attributes` *(self, obj, attributes)*:9394 Get some attributes from the object. If `attributes` is an empty95 sequence the object itself is returned unchanged.9697**def** `call_function` *(self, f, context, args, kwargs, dyn_args, dyn_kwargs)*:98 99 Call a function `f` with the arguments `args`, `kwargs`, `dyn_args` and100 `dyn_kwargs` where `args` is a tuple and `kwargs` a dict. If `dyn_args`
1 unmodified line
102 not `None` you have to update the `kwargs` with it.103104 The default implementation performs some security checks.10595 **Warning** this is a jinja internal method. The actual implementation106 **Warning** this is a Jinja internal method. The actual implementation107 and function signature might change.108109**def** `call_function_simple` *(self, f, context)*:110111 Like `call_function` but without arguments.112102 **Warning** this is a jinja internal method. The actual implementation113 **Warning** this is a Jinja internal method. The actual implementation114 and function signature might change.115116**def** `finish_var` *(self, value, ctx)*:117118 Postprocess a variable before it's sent to the template.119109 **Warning** this is a jinja internal method. The actual implementation120 **Warning** this is a Jinja internal method. The actual implementation121 and function signature might change.122 123.. admonition:: Note124
49 unmodified lines
modified:docs/src/designerdoc.txt+14 added
920 unmodified lines
921 {% else %}922 one user found.923 {% endif %}924925*New in Jinja 1.1*: It's now possible to use the marker name as implicit926default:927928.. sourcecode:: jinja929930 instead of this version:931932 {% trans username=username %}Hello {{ username }}!{% endtrans %}933934 you can now write this:935936 {% trans username %}Hello {{ username }}!{% endtrans %}937938939.. _slicing chapter: http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice940.. _range function: http://docs.python.org/tut/node6.html#SECTION006300000000000000000
modified:docs/src/frameworks.txt+116 added-3 removed
1=====================2Framework Integration3=====================45Because the buffet template interface does not support more complex usage6cases there is currently no built in framework support. This however will7hopefully change before the Jinja release.5Starting with Jinja 1.1 it's possible to embed Jinja into some of the existing6frameworks a lot easier. When speaking of frameworks we only refer to `Pylons`_7which has a working implementation of the TurboGears template specification.89Since the whole situation is problematic because of various reasons (kid10specific, uses dotted names for template loading, package name prefix etc.)11we worked around some of the problems by using pylons specific workarounds.1213Jinja also ships an implementation for a hypothetical template abstraction layer14called `General Template Interface`_ which isn't implemented by any existing15framework so far. This specification however tries to solve the problems that16exist in Buffet.1718Buffet19======2021The buffet specification proposes that templates are named in dotted names. That22means `foo.bar` and not `foo/bar.html`. The dotted notation has the disadvantage23that you cannot specify the filename extension. In recent pylons versions it's24however possible to load templates with their native path too if you prefix the25template name with a foreslash (`/foo/bar.html`). If you don't specify the26extension it will assume `.html` for the dotted notation.2728Here the list of configuration values:2930======================= ======================================================31``jinja.extension`` The template extension when templates are loaded using32 the dotted notation. Defaults to ``html``.33``jinja.environment`` If this is provided it must be the only configuration34 value and it's used as jinja environment. In that35 case all other configuration parameters except of36 ``jinja.extension`` are ignored.37``jinja.searchpath`` If provided a new file system loader with this38 search path is instanciated.39``jinja.package`` Name of the python package containing the40 templates. If this and ``package_path`` is41 defined a `PackageLoader` is used.42``jinja.package_path`` Path to the templates inside of a package.43``jinja.loader_func`` Function that takes the name of the template to44 load. If it returns a string or unicode object45 it's used to load a template. If the return46 value is None it's considered missing.47``jinja.getmtime_func`` Function used to check if templates requires48 reloading. Has to return the UNIX timestamp of49 the last template change or 0 if this template50 does not exist or requires updates at any cost.51``jinja.use_memcache`` Set this to ``True`` to enable memory caching.52 This is usually a good idea in production mode,53 but disable it during development since it won't54 reload template changes automatically.55 This only works in persistent environments like56 FastCGI.57``jinja.memcache_size`` Number of template instance you want to cache.58 Defaults to ``40``.59``jinja.cache_folder`` Set this to an existing directory to enable60 caching of templates on the file system. Note61 that this only affects templates transformed62 into python code. Default is ``None`` which means63 that caching is disabled.64``jinja.auto_reload`` Set this to `False` for a slightly better65 performance. In that case of `getmtime_func`66 not being provided this won't have an effect.67======================= ======================================================6869All other options that start with `jinja.` are automatically forwarded to the70environment constructor.7172In pylons for example you can use jinja as buffet plugin like this:7374Edit the `yourproject/config/middleware.py` and add this to `config.init_app`:7576.. sourcecode:: python7778 config.add_template_engine('jinja', '', {79 'jinja.package': 'yourapplication',80 'jinja.package_path': 'res/templates',81 'jinja.use_memcache': True82 })8384Note that it's a good idea to set the second parameter to an empty string.85It's meant to be used as replacement for the turbogears package name but86Jinja assumes that the name of the template does not include the package87path.8889You can then render the template in the view like this:9091.. sourcecode:: python9293 class ExampleController(BaseController):9495 def index(self):96 c.title = "Your Page"97 c.message = 'hi'98 return render_response('jinja', 'test_template')99100 def download(self):101 c.title = "Downloads"102 c.downloads = [1, 2, 3]103 return render_response('jinja', '/downloads.html')104105With the settings from above rendering the `index` action will result in106rendering the template ``res/templates/test_template.html`` where res is107a folder in the ``yourapplication`` python package.108109The `downloads` action uses the pylons specific leading foreslash notation.110111General Template Interface112==========================113114Because nobody implemented this specification so far it's not documented here115but in the sourcecode of the `plugin module`_. The specification itself is116explained on the pocoo trac on the `General Template Interface`_ wiki page.117118.. _Pylons: http://www.pylonshq.com/119.. _General Template Interface: http://trac.pocoo.org/wiki/GeneralTemplateInterface120.. _plugin module: http://trac.pocoo.org/browser/jinja/trunk/jinja/plugin.py
modified:docs/src/i18n.txt+5 added
68 unmodified lines
69singular form and the third is the plural form if given.7071Because Jinja is not bound to gettext you can now use these strings to72create translation files for any translation system.7374*New in Jinja 1.1* You can now extract translations from strings according75to the current envrionment settings too by using the environment method76`get_translations_for_string` which takes a string containing a template77as only argument. The return value is the same as for `get_translations`.
modified:docs/src/index.txt+2 added
28 unmodified lines
29 - `Debugging Support <debugging.txt>`_3031 - `Internationalization <i18n.txt>`_3233 - `Alternative Syntax <altsyntax.txt>`_3435 - `Developer Recipies <devrecipies.txt>`_3637- Template Designer Documentation:38
9 unmodified lines
modified:docs/generate.py+1 added-1 removed
244 unmodified lines
245 parts = publish_parts(246 data,247 writer=writer,248 settings_overrides={249 'initial_header_level': 3,249 'initial_header_level': 2,250 'field_name_limit': 50,251 }252 )253 return {
46 unmodified lines
modified:jinja/translators/python.py+9 added-20 removed
312 unmodified lines
313 return out314315 def reset(self):316 """317 Reset translation variables such as indention, cycle id318 or the require_translations flag.317 Reset translation variables such as indention or cycle id318 """319 self.indention = 0320 self.last_cycle_id = 0322 self.require_translations = False321322 def translate(self):323 """324 Translate the node defined in the constructor after
84 unmodified lines
409410 # the template body411 body_lines.extend([self.handle_node(n) for n in node])412415 # add translation helpers if required416 if self.require_translations:417 lines.append(418 ' translator = environment.get_translator(context)\n'419 ' def translate(s, p=None, n=None, r=None):\n'420 ' if p is None:\n'421 ' return translator.gettext(s) % (r or {})\n'422 ' return translator.ngettext(s, p, r[n]) % (r or {})\n'423 ' context.translate_func = translate'424 )425413 # add body lines and "generator hook"414 lines.extend(body_lines)415 lines.append(' if False:\n yield None')416
61 unmodified lines
478 def handle_node_list(self, node):479 """480 In some situations we might have a node list. It's just481 a collection of multiple statements.482483 If the nodelist was empty it will return an empty string484 """496 return '\n'.join([self.indent(self.nodeinfo(node))] +497 [self.handle_node(n) for n in node])485 body = '\n'.join([self.handle_node(n) for n in node])486 if body:487 return self.indent(self.nodeinfo(node)) + '\n' + body488 return ''489490 def handle_for_loop(self, node):491 """492 Handle a for loop. Pretty basic, just that we give the else
67 unmodified lines
560 self.handle_node(test)561 ))562 self.indention += 1563 write(self.nodeinfo(body))573 buf.append(self.handle_node(body))564 buf.append(self.handle_node(body) or self.indent('pass'))565 self.indention -= 1566 if node.else_ is not None:567 write('else:')568 self.indention += 1569 write(self.nodeinfo(node.else_))579 buf.append(self.handle_node(node.else_))570 buf.append(self.handle_node(node.else_) or self.indent('pass'))571 self.indention -= 1572 return '\n'.join(buf)573574 def handle_cycle(self, node):
154 unmodified lines
729 def handle_trans(self, node):730 """731 Handle translations.732 """742 self.require_translations = True733 if node.replacements:734 replacements = []735 for name, n in node.replacements.iteritems():736 replacements.append('%r: %s' % (
29 unmodified lines
766 """767 if node.name in self.constants:768 return self.constants[node.name]769 elif node.name == '_':780 self.require_translations = True770 return 'context.translate_func'771 return 'context[%r]' % node.name772773 def handle_compare(self, node):
273 unmodified lines
modified:jinja/datastructure.py+61 added-5 removed
187 unmodified lines
188 def __init__(self, _environment_, *args, **kwargs):189 self.environment = _environment_190 self._stack = [_environment_.globals, dict(*args, **kwargs), {}]191 self.globals, self.initial, self.current = self._stack192 self._translate_func = None193193 # translator function added by the environment rendering function194 self.translate_func = None195194 # cache object used for filters and tests195 self.cache = {}196197 def translate_func(self):198 """199 Return the translator for this context.200 """201 if self._translate_func is None:202 translator = self.environment.get_translator(self)203 def translate(s, p=None, n=None, r=None):204 if p is None:205 return translator.gettext(s) % (r or {})206 return translator.ngettext(s, p, r[n]) % (r or {})207 self._translate_func = translate208 return self._translate_func209 translate_func = property(translate_func, doc=translate_func.__doc__)210211 def pop(self):212 """213 Pop the last layer from the stack and return it.214 """
200 unmodified lines
415 def __repr__(self):416 return '<SuperBlock %r>' % self.name417418419class StateTest(object):420 """421 Wrapper class for basic lambdas in order to simplify422 debugging in the parser. It also provides static helper423 functions that replace some lambda expressions424 """425426 def __init__(self, func, error_message):427 self.func = func428 self.error_message = error_message429430 def __call__(self, p, t, d):431 return self.func(p, t, d)432433 def expect_token(token_name, error_message=None):434 """Scans until a token types is found."""435 return StateTest(lambda p, t, d: t == token_name, 'expected ' +436 (error_message or token_name))437 expect_token = staticmethod(expect_token)438439 def expect_name(*names):440 """Scans until one of the given names is found."""441 if len(names) == 1:442 name = names[0]443 return StateTest(lambda p, t, d: t == 'name' and d == name,444 "expected '%s'" % name)445 else:446 return StateTest(lambda p, t, d: t == 'name' and d in names,447 'expected one of %s' % ','.join(["'%s'" % name448 for name in names]))449 expect_name = staticmethod(expect_name)450451452class TokenStream(object):453 """454 A token stream works like a normal generator just that455 it supports pushing tokens back to the stream.456 """457413 def __init__(self, generator):458 def __init__(self, generator, filename):459 self._next = generator.next460 self._pushed = []461 self.last = (1, 'initial', '')462 self.filename = filename463464 def bound(self):465 """Return True if the token stream is bound to a parser."""466 return self.parser is not None467 bound = property(bound, doc=bound.__doc__)468469 def __iter__(self):470 """Return self in order to mark this is iterator."""471 return self472
35 unmodified lines
508 return509 else:510 yield token511 except StopIteration:512 if isinstance(test, StateTest):513 msg = ': ' + test.error_message514 else:515 msg = ''461 raise TemplateSyntaxError('end of stream reached')516 raise TemplateSyntaxError('end of stream' + msg,517 self.last[0], self.filename)518519 def drop_until(self, test, drop_needle=False):520 """Fetch tokens until a function matches and drop all521 tokens."""
55 unmodified lines
modified:jinja/environment.py+11 added-2 removed
134 unmodified lines
135 self.silent = silent136 self.friendly_traceback = friendly_traceback137138 # global namespace139 self.globals = namespace is None and DEFAULT_NAMESPACE.copy() \140 or namespace139 if namespace is None:140 self.globals = DEFAULT_NAMESPACE.copy()141 else:142 self.globals = namespace143144 # jinja 1.0 compatibility145 if auto_escape:146 self.default_filters.append(('escape', (True,)))
81 unmodified lines
228 the parent or any included templates!)229 """230 return collect_translations(self.loader.parse(name))231232 def get_translations_for_string(self, string):233 """234 Like `get_translations`, but the translations are loaded from a235 normal string that represents the template.236 """237 return collect_translations(self.parse(string))238239 def apply_filters(self, value, context, filters):240 """241 Apply a list of filters on the variable.242 """
95 unmodified lines
modified:jinja/filters.py+5 added-2 removed
658 unmodified lines
659660def do_striptags(value, rex=re.compile(r'<[^>]+>')):661 """662 Strip SGML/XML tags and replace adjacent whitespace by one space.663 663664 *new in Jinja 1.1*665 """666 return ' '.join(rex.sub('', value).split())667do_striptags = stringfilter(do_striptags)
131 unmodified lines
799 if method == 'common':800 return round(value, precision)801 import math802 func = getattr(math, method)803 if precision:803 return func(value * 10 * precision) / (10 * precision)804 return func(value * 10 * precision) / (10 * precision)805 else:806 return func(value)807 return wrapped808809810FILTERS = {
45 unmodified lines
modified:jinja/lexer.py+143 added-75 removed
23 unmodified lines
24"""25import re26from jinja.datastructure import TokenStream27from jinja.exceptions import TemplateSyntaxError28from weakref import WeakValueDictionary2930try:31 set32except NameError:
2 unmodified lines
3536__all__ = ['Lexer', 'Failure', 'keywords']373839# cache for the lexers. Exists in order to be able to have multiple40# environments with the same lexer41_lexer_cache = WeakValueDictionary()424344# static regular expressions45whitespace_re = re.compile(r'\s+(?m)')46name_re = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*')47string_re = re.compile(r"('([^'\\]*(?:\\.[^'\\]*)*)'"
32 unmodified lines
80 def __call__(self, lineno):81 raise self.error_class(self.message, lineno)828384class LexerMeta(type):85 """86 Metaclass for the lexer that caches instances for87 the same configuration in a weak value dictionary.88 """8990 def __call__(cls, environment):91 key = hash((environment.block_start_string,92 environment.block_end_string,93 environment.variable_start_string,94 environment.variable_end_string,95 environment.comment_start_string,96 environment.comment_end_string,97 environment.trim_blocks))9899 # use the cached lexer if possible100 if key in _lexer_cache:101 return _lexer_cache[key]102103 # create a new lexer and cache it104 lexer = type.__call__(cls, environment)105 _lexer_cache[key] = lexer106 return lexer107108109class Lexer(object):110 """111 Class that implements a lexer for a given environment. Automatically112 created by the environment class, usually you don't have to do that.113114 Note that the lexer is not automatically bound to an environment.115 Multiple environments can share the same lexer.116 """117118 __metaclass__ = LexerMeta119120 def __init__(self, environment):121 # shortcuts122 c = lambda x: re.compile(x, re.M | re.S)123 e = re.escape
48 unmodified lines
172 block_suffix_re173 )), ('comment', 'comment_end'), '#pop'),174 (c('(.)'), (Failure('Missing end of comment tag'),), None)175 ],140 # directives176 # blocks177 'block_begin': [178 (c('(?:\-%s\s*|%s)%s' % (179 e(environment.block_end_string),180 e(environment.block_end_string),
19 unmodified lines
200 (c('(.)'), (Failure('Missing end of raw directive'),), None)201 ]202 }203168 def tokenize(self, source):204 def tokenize(self, source, filename=None):205 """206 Simple tokenize function that yields ``(position, type, contents)``207 tuples. Wrap the generator returned by this function in a208 `TokenStream` to get real token instances and be able to push tokens
1 unmodified line
210211 Additionally non keywords are escaped.212 """213 def generate():178 for lineno, token, value in self.tokeniter(source):214 for lineno, token, value in self.tokeniter(source, filename):215 if token == 'name' and value not in keywords:216 value += '_'217 yield lineno, token, value182 return TokenStream(generate())218 return TokenStream(generate(), filename)219184 def tokeniter(self, source):220 def tokeniter(self, source, filename=None):221 """222 This method tokenizes the text and returns the tokens in a generator.223 Use this method if you just want to tokenize a template. The output224 you get is not compatible with the input the jinja parser wants. The
6 unmodified lines
231 stack = ['root']232 statetokens = self.rules['root']233 source_length = len(source)234235 balancing_stack = []236237 while True:238 # tokenizer loop239 for regex, tokens, new_state in statetokens:240 m = regex.match(source, pos)203 if m:204 # tuples support more options205 if isinstance(tokens, tuple):206 for idx, token in enumerate(tokens):207 # hidden group208 if token is None:209 g = m.group(idx)210 if g:211 lineno += g.count('\n')212 continue213 # failure group214 elif isinstance(token, Failure):215 raise token(m.start(idx + 1))216 # bygroup is a bit more complex, in that case we217 # yield for the current token the first named218 # group that matched219 elif token == '#bygroup':220 for key, value in m.groupdict().iteritems():221 if value is not None:222 yield lineno, key, value223 lineno += value.count('\n')224 break225 else:226 raise RuntimeError('%r wanted to resolve '227 'the token dynamically'228 ' but no group matched'229 % regex)230 # normal group231 else:232 data = m.group(idx + 1)233 if data:234 yield lineno, token, data235 lineno += data.count('\n')236 # strings as token just are yielded as it, but just237 # if the data is not empty238 else:239 data = m.group()240 if tokens is not None:241 if data:242 yield lineno, tokens, data243 lineno += data.count('\n')244 # fetch new position into new variable so that we can check245 # if there is a internal parsing error which would result246 # in an infinite loop247 pos2 = m.end()248 # handle state changes249 if new_state is not None:250 # remove the uppermost state251 if new_state == '#pop':252 stack.pop()253 # resolve the new state by group checking254 elif new_state == '#bygroup':241 # if no match we try again with the next rule242 if not m:243 continue244245 # we only match blocks and variables if brances / parentheses246 # are balanced. continue parsing with the lower rule which247 # is the operator rule. do this only if the end tags look248 # like operators249 if balancing_stack and \250 tokens in ('variable_end', 'block_end'):251 continue252253 # tuples support more options254 if isinstance(tokens, tuple):255 for idx, token in enumerate(tokens):256 # hidden group257 if token is None:258 g = m.group(idx)259 if g:260 lineno += g.count('\n')261 continue262 # failure group263 elif isinstance(token, Failure):264 raise token(m.start(idx + 1))265 # bygroup is a bit more complex, in that case we266 # yield for the current token the first named267 # group that matched268 elif token == '#bygroup':269 for key, value in m.groupdict().iteritems():270 if value is not None:257 stack.append(key)271 yield lineno, key, value272 lineno += value.count('\n')273 break274 else:260 raise RuntimeError('%r wanted to resolve the '261 'new state dynamically but'262 ' no group matched' %263 regex)264 # direct state name given275 raise RuntimeError('%r wanted to resolve '276 'the token dynamically'277 ' but no group matched'278 % regex)279 # normal group280 else:281 data = m.group(idx + 1)282 if data:283 yield lineno, token, data284 lineno += data.count('\n')285286 # strings as token just are yielded as it, but just287 # if the data is not empty288 else:289 data = m.group()290 # update brace/parentheses balance291 if tokens == 'operator':292 if data == '{':293 balancing_stack.append('}')294 elif data == '(':295 balancing_stack.append(')')296 elif data == '[':297 balancing_stack.append(']')298 elif data in ('}', ')', ']'):299 if not balancing_stack or \300 balancing_stack.pop() != data:301 raise TemplateSyntaxError('unexpected EOF '302 'while lexing',303 lineno, filename)304 # yield items305 if tokens is not None:306 if data:307 yield lineno, tokens, data308 lineno += data.count('\n')309310 # fetch new position into new variable so that we can check311 # if there is a internal parsing error which would result312 # in an infinite loop313 pos2 = m.end()314315 # handle state changes316 if new_state is not None:317 # remove the uppermost state318 if new_state == '#pop':319 stack.pop()320 # resolve the new state by group checking321 elif new_state == '#bygroup':322 for key, value in m.groupdict().iteritems():323 if value is not None:324 stack.append(key)325 break326 else:327 raise RuntimeError('%r wanted to resolve the '328 'new state dynamically but'329 ' no group matched' %330 regex)331 # direct state name given332 else:266 stack.append(new_state)267 statetokens = self.rules[stack[-1]]268 # we are still at the same position and no stack change.269 # this means a loop without break condition, avoid that and270 # raise error271 elif pos2 == pos:272 raise RuntimeError('%r yielded empty string without '273 'stack change' % regex)274 # publish new function and start again275 pos = pos2276 break333 stack.append(new_state)334 statetokens = self.rules[stack[-1]]335 # we are still at the same position and no stack change.336 # this means a loop without break condition, avoid that and337 # raise error338 elif pos2 == pos:339 raise RuntimeError('%r yielded empty string without '340 'stack change' % regex)341 # publish new function and start again342 pos = pos2343 break344 # if loop terminated without break we havn't found a single match345 # either we are at the end of the file or we have a problem346 else:347 # end of text348 if pos >= source_length:349 return350 # something went wrong351 raise TemplateSyntaxError('unexpected char %r at %d' %285 (source[pos], pos), lineno)352 (source[pos], pos), lineno,353 filename)
modified:jinja/parser.py+92 added-39 removed
16 unmodified lines
17import re18from compiler import ast, parse19from compiler.misc import set_filename20from jinja import nodes21from jinja.datastructure import TokenStream21from jinja.datastructure import TokenStream, StateTest22from jinja.exceptions import TemplateSyntaxError23try:24 set25except NameError:
2 unmodified lines
2829__all__ = ['Parser']303132# callback functions for the subparse method33end_of_block = lambda p, t, d: t == 'block_end'34end_of_variable = lambda p, t, d: t == 'variable_end'35end_of_comment = lambda p, t, d: t == 'comment_end'36switch_for = lambda p, t, d: t == 'name' and d in ('else', 'endfor')37end_of_for = lambda p, t, d: t == 'name' and d == 'endfor'38switch_if = lambda p, t, d: t == 'name' and d in ('else', 'elif', 'endif')39end_of_if = lambda p, t, d: t == 'name' and d == 'endif'40end_of_filter = lambda p, t, d: t == 'name' and d == 'endfilter'41end_of_macro = lambda p, t, d: t == 'name' and d == 'endmacro'42end_of_block_tag = lambda p, t, d: t == 'name' and d == 'endblock'43end_of_trans = lambda p, t, d: t == 'name' and d == 'endtrans'32# general callback functions for the parser33end_of_block = StateTest.expect_token('block_end', 'end of block tag')34end_of_variable = StateTest.expect_token('variable_end', 'end of variable')35end_of_comment = StateTest.expect_token('comment_end', 'end of comment')3637# internal tag callbacks38switch_for = StateTest.expect_name('else', 'endfor')39end_of_for = StateTest.expect_name('endfor')40switch_if = StateTest.expect_name('else', 'elif', 'endif')41end_of_if = StateTest.expect_name('endif')42end_of_filter = StateTest.expect_name('endfilter')43end_of_macro = StateTest.expect_name('endmacro')44end_of_block_tag = StateTest.expect_name('endblock')45end_of_trans = StateTest.expect_name('endtrans')464748class Parser(object):49 """50 The template parser class.51
3 unmodified lines
55 def __init__(self, environment, source, filename=None):56 self.environment = environment57 if isinstance(source, str):58 source = source.decode(environment.template_charset, 'ignore')59 if isinstance(filename, unicode):60 filename = filename.encode('utf-8')61 self.source = source62 self.filename = filename59 self.tokenstream = environment.lexer.tokenize(source)6364 #: if this template has a parent template it's stored here65 #: after parsing66 self.extends = None67 #: set for blocks in order to keep them unique68 self.blocks = set()6970 #: mapping of directives that require special treatment71 self.directives = {72 'raw': self.handle_raw_directive,73 'for': self.handle_for_directive,74 'if': self.handle_if_directive,
7 unmodified lines
82 'include': self.handle_include_directive,83 'trans': self.handle_trans_directive84 }8586 #: set of directives that are only available in a certain87 #: context.88 self.context_directives = set(['elif', 'else', 'endblock',89 'endfilter', 'endfor', 'endif', 'endmacro', 'endraw',90 'endtrans', 'pluralize'91 ])9293 self.tokenstream = environment.lexer.tokenize(source, filename)9495 def handle_raw_directive(self, lineno, gen):96 """97 Handle fake raw directive. (real raw directives are handled by98 the lexer. But if there are arguments to raw or the end tag
256 unmodified lines
355 first_var = None356 replacements = {}357 for arg in self.parse_python(lineno, gen,358 '_trans(%s)').expr.args:346 if arg.__class__ is not ast.Keyword:359 if arg.__class__ not in (ast.Keyword, ast.Name):360 raise TemplateSyntaxError('translation tags need expl'361 'icit names for values.',362 lineno, self.filename)363 # disallow keywords364 if not arg.name.endswith('_'):352 raise TemplateSyntaxError('illegal use of keyword %r '353 'as identifier.' % arg.name,354 lineno, self.filename)365 raise TemplateSyntaxError("illegal use of keyword '%s"366 '\' as identifier.' %367 arg.name, lineno,368 self.filename)369 # remove the last "_" before writing370 name = arg.name[:-1]371 if first_var is None:357 first_var = arg.name[:-1]358 replacements[arg.name[:-1]] = arg.expr372 first_var = name373 # if it's a keyword use the expression as value,374 # otherwise just reuse the name node.375 replacements[name] = getattr(arg, 'expr', arg)376377 # look for endtrans/pluralize378 buf = singular = []379 plural = indicator = None
14 unmodified lines
394 self.filename)395 # plural name without trailing "_"? that's a keyword396 if not variable_name.endswith('_'):397 raise TemplateSyntaxError('illegal use of keyword '381 '%r as identifier in trans '382 'block.' % variable_name,398 "'%s' as identifier in "399 'trans block.' %400 variable_name,401 lineno, self.filename)402 variable_name = variable_name[:-1]403 if variable_name not in replacements:404 raise TemplateSyntaxError('unregistered translation '387 'variable %r.' %405 "variable '%s'." %406 variable_name, lineno,407 self.filename)408 if self.tokenstream.next()[1] != 'variable_end':409 raise TemplateSyntaxError('you cannot use variable '
6 unmodified lines
416 elif token == 'block_begin':417 _, block_token, block_name = self.tokenstream.next()418 if block_token != 'name' or \419 block_name not in ('pluralize', 'endtrans'):420 # if we have a block name check if it's a real421 # directive or a not existing one (which probably422 # is a typo)423 if block_token == 'name':424 # if this block is a context directive the425 # designer has probably misspelled endtrans426 # with endfor or something like that. raise427 # a nicer error message428 if block_name in self.context_directives:429 raise TemplateSyntaxError('unexpected directi'430 "ve '%s' found" %431 block_name, lineno,432 self.filename)433 # if's not a directive, probably misspelled434 # endtrans. Raise the "unknown directive"435 # exception rather than the "not allowed"436 if block_name not in self.directives:437 if block_name.endswith('_'):438 block_name = block_name[:-1]439 raise TemplateSyntaxError('unknown directive'440 "'%s'" % block_name,441 lineno,442 self.filename)443 # if it's indeed a known directive we better444 # raise an exception informing the user about445 # the fact that we don't support blocks in446 # translatable sections.402 raise TemplateSyntaxError('blocks in translatable '403 'sections are not '404 'supported', lineno,447 raise TemplateSyntaxError('directives in translatable'448 ' sections are not '449 'allowed', lineno,450 self.filename)451 # pluralize452 if block_name == 'pluralize':453 if plural is not None:
7 unmodified lines
461 elif plural_token == 'name':462 # disallow keywords463 if not plural_name.endswith('_'):464 raise TemplateSyntaxError('illegal use of '420 'keyword %r as '465 "keyword '%s' as "466 'identifier.' %467 plural_name,468 lineno,469 self.filename)470 plural_name = plural_name[:-1]471 if plural_name not in replacements:472 raise TemplateSyntaxError('unregistered '473 'translation '429 'variable %r' %474 "variable '%s'" %475 plural_name, lineno,476 self.filename)477 elif self.tokenstream.next()[1] != 'block_end':478 raise TemplateSyntaxError('pluralize takes '
52 unmodified lines
531 encode('utf-8'))532 try:533 ast = parse(source, 'exec')534 except SyntaxError, e:490 raise TemplateSyntaxError('invalid syntax', lineno + e.lineno,535 raise TemplateSyntaxError('invalid syntax in expression',536 lineno + (e.lineno or 0),537 self.filename)492 assert len(ast.node.nodes) == 1, 'get %d nodes, 1 expected' %\538 assert len(ast.node.nodes) == 1, 'get %d nodes, 1 expected' % \539 len(ast.node.nodes)540 result = ast.node.nodes[0]541 nodes.inc_lineno(lineno, result)542 return result
10 unmodified lines
553 node = todo.pop()554 # all names excluding keywords have an trailing underline.555 # if we find a name without trailing underline that's a keyword556 # and this code raises an error. else strip the underline again511 if node.__class__ in (ast.AssName, ast.Name):557 if node.__class__ in (ast.AssName, ast.Name, ast.Keyword):558 if not node.name.endswith('_'):559 raise TemplateSyntaxError('illegal use of keyword %r '560 'as identifier.' % node.name,561 node.lineno, self.filename)
69 unmodified lines
631 # if if doesn't match any existing directive it's like a632 # template syntax error.633 if data in self.directives:634 node = self.directives[data](lineno, gen)589 # directive or endtag found, give a proper error message590 elif data in self.directives or \591 not data.endswith('_') and data.startswith('end'):635 # context depending directive found636 elif data in self.context_directives:637 raise TemplateSyntaxError('unexpected directive %r' %638 str(data), lineno,639 self.filename)640 # keyword or unknown name with trailing slash
20 unmodified lines
661 data))662663 # still here and a test function is provided? raise and error664 if test is not None:665 # if the callback is a state test lambda wrapper we666 # can use the `error_message` property to get the error667 if isinstance(test, StateTest):668 msg = ': ' + test.error_message669 else:670 msg = ''620 raise TemplateSyntaxError('unexpected end of template', lineno,621 self.filename)671 raise TemplateSyntaxError('unexpected end of template' + msg,672 lineno, self.filename)673 return finish()674675 def close_remaining_block(self):676 """
1 unmodified line
678 tag we can use this method to drop the rest of the block from679 the stream. If the next token isn't the block end we throw an680 error.681 """631 lineno = self.tokenstream.last[0]682 lineno, _, tagname = self.tokenstream.last683 try:684 lineno, token, data = self.tokenstream.next()685 except StopIteration:686 raise TemplateSyntaxError('missing closing tag', lineno,687 self.filename)688 if token != 'block_end':638 raise TemplateSyntaxError('expected close tag, found %r' % token,639 lineno, self.filename)689 print token, data, list(self.tokenstream)690 raise TemplateSyntaxError('expected empty %s-directive but '691 'found additional arguments.' %692 tagname, lineno, self.filename)
modified:jinja/plugin.py+60 added-1 removed
1 unmodified line
2"""3 jinja.plugin4 ~~~~~~~~~~~~56 Support for the `GeneralTemplateInterface`__.6 Support for the `GeneralTemplateInterface`__ and the Buffet interface.78 Do not use this module on your own. We don't recommend those interfaces!9 If you are able to, you should really use Jinja without those abstraction10 layers.1112 __ http://trac.pocoo.org/wiki/GeneralTemplateInterface1314 :copyright: 2007 by Armin Ronacher.15 :license: BSD, see LICENSE for more details.
2 unmodified lines
18from jinja.loaders import FunctionLoader, FileSystemLoader, PackageLoader19from jinja.exceptions import TemplateNotFound202122class BuffetPlugin(object):23 """24 Implements the Jinja buffet plugin. Well. It works for pylons and should25 work for TurboGears too if their plugin system would work.26 """2728 def __init__(self, extra_vars_func=None, options=None):29 if 'jinja.environment' in options:30 self.env = options['jinja.environment']31 else:32 opt = {}33 for key, value in options.iteritems():34 if key.startswith('jinja.') and key != 'jinja.extension':35 opt[key[6:]] = value36 loader_func = opt.pop('loader_func', None)37 getmtime_func = opt.pop('getmtime_func', None)38 use_memcache = opt.pop('use_memcache', False)39 memcache_size = opt.pop('memcache_size', 40)40 cache_folder = opt.pop('cache_folder', None)41 auto_reload = opt.pop('auto_reload', True)42 if 'searchpath' in options:43 opt['loader'] = FileSystemLoader(opt.pop('searchpath'),44 use_memcache, memcache_size,45 cache_folder, auto_reload)46 elif 'package' in options:47 opt['loader'] = PackageLoader(opt.pop('package'),48 opt.pop('package_path', ''),49 use_memcache, memcache_size,50 cache_folder, auto_reload)51 elif loader_func is not None:52 opt['loader'] = FunctionLoader(loader_func, getmtime_func,53 use_memcache, memcache_size,54 cache_folder, auto_reload)55 self.env = Environment(**opt)5657 self.extra_vars_func = extra_vars_func58 self.extension = options.pop('jinja.extension', 'html')5960 def load_template(self, templatename, template_string=None):61 if template_string is not None:62 return self.env.from_string(template_string)63 if templatename.startswith('!'):64 jinja_name = templatename[1:]65 else:66 jinja_name = templatename.replace('.', '/') + '.' + self.extension67 return self.env.get_template(jinja_name)6869 def render(self, info, format='html', fragment=False, template=None):70 if isinstance(template, basestring):71 template = self.load_template(template)72 if self.extra_vars_func:73 info.update(self.extra_vars_func())74 return template.render(info)757677def jinja_plugin_factory(options):78 """79 Basic implementation of the `GeneralTemplateInterface`.80
81 unmodified lines
modified:jinja/tests.py+1 added
110 unmodified lines
111 return False112 return regex.search(value) is not None113 return wrapped114115116TESTS = {117 'odd': test_odd,118 'even': test_even,119 'defined': test_defined,
6 unmodified lines
modified:tests/test_filters.py+54 added
20 unmodified lines
21{{ false|default('no', true) }}|{{ given|default("no") }}'''22DICTSORT = '''{{ foo|dictsort }}|\23{{ foo|dictsort(true) }}|\24{{ foo|dictsort(false, 'value') }}'''25BATCH = '''{{ foo|batch(3) }}|{{ foo|batch(3, 'X') }}'''26SLICE = '''{{ foo|slice(3) }}|{{ foo|slice(3, 'X') }}'''27ESCAPE = '''{{ '<">&'|escape }}|{{ '<">&'|escape(true) }}'''28STRIPTAGS = '''{{ foo|striptags }}'''29FILESIZEFORMAT = '{{ 100|filesizeformat }}|\30{{ 1000|filesizeformat }}|\31{{ 1000000|filesizeformat }}|\32{{ 1000000000|filesizeformat }}|\
21 unmodified lines
54URLIZE = '''{{ "foo http://www.example.com/ bar"|urlize }}'''55WORDCOUNT = '''{{ "foo bar baz"|wordcount }}'''56BLOCK = '''{% filter lower|escape %}<HEHE>{% endfilter %}'''57CHAINING = '''{{ ['<foo>', '<bar>']|first|upper|escape }}'''58SUM = '''{{ [1, 2, 3, 4, 5, 6]|sum }}'''59ABS = '''{{ -1|abs }}|{{ 1|abs }}'''60ROUND = '''{{ 2.7|round }}|{{ 2.1|round }}|\61{{ 2.1234|round(2, 'floor') }}|{{ 2.1|round(0, 'ceil') }}'''62XMLATTR = '''{{ {'foo': 42, 'bar': 23, 'fish': none,63'spam': missing, 'blub:blub': '<?>'}|xmlattr }}'''646566def test_capitalize(env):67 tmpl = env.from_string(CAPITALIZE)
22 unmodified lines
90 "[('A', 3), ('a', 0), ('b', 1), ('c', 2)]|"91 "[('a', 0), ('b', 1), ('c', 2), ('A', 3)]")929394def test_batch(env):95 tmpl = env.from_string(BATCH)96 out = tmpl.render(foo=range(10))97 assert out == ("[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]|"98 "[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 'X', 'X']]")99100101def test_slice(env):102 tmpl = env.from_string(SLICE)103 out = tmpl.render(foo=range(10))104 assert out == ("[[0, 1, 2, 3], [4, 5, 6], [7, 8, 9]]|"105 "[[0, 1, 2, 3], [4, 5, 6, 'X'], [7, 8, 9, 'X']]")106107108def test_escape(env):109 tmpl = env.from_string(ESCAPE)110 out = tmpl.render()111 assert out == '&lt;"&gt;&amp;|&lt;&quot;&gt;&amp;'112113114def test_striptags(env):115 tmpl = env.from_string(STRIPTAGS)116 out = tmpl.render(foo=' <p>just a small \n <a href="#">'117 'example</a> link</p>\n<p>to a webpage</p>')118 assert out == 'just a small example link to a webpage'119120121def test_filesizeformat(env):122 tmpl = env.from_string(FILESIZEFORMAT)123 out = tmpl.render()124 assert out == '100 Bytes|1000 Bytes|976.6 KB|953.7 MB|931.3 GB'
124 unmodified lines
249250def test_chaining(env):251 tmpl = env.from_string(CHAINING)252 assert tmpl.render() == '&lt;FOO&gt;'253254255def test_sum(env):256 tmpl = env.from_string(SUM)257 assert tmpl.render() == '21'258259260def test_abs(env):261 tmpl = env.from_string(ABS)262 return tmpl.render() == '1|1'263264265def test_round(env):266 tmpl = env.from_string(ROUND)267 return tmpl.render() == '3.0|2.0|2.1|3.0'268269270def test_xmlattr(env):271 tmpl = env.from_string(XMLATTR)272 out = tmpl.render().split()273 assert len(out) == 3274 assert 'foo="42"' in out275 assert 'bar="23"' in out276 assert 'blub:blub="&lt;?&gt;"' in out
modified:tests/test_ifcondition.py+6 added
8 unmodified lines
910SIMPLE = '''{% if true %}...{% endif %}'''11ELIF = '''{% if false %}XXX{% elif true %}...{% else %}XXX{% endif %}'''12ELSE = '''{% if false %}XXX{% else %}...{% endif %}'''13EMPTY = '''[{% if true %}{% else %}{% endif %}]'''141516def test_simple(env):17 tmpl = env.from_string(SIMPLE)
7 unmodified lines
2526def test_else(env):27 tmpl = env.from_string(ELSE)28 assert tmpl.render() == '...'293031def test_empty(env):32 tmpl = env.from_string(EMPTY)33 assert tmpl.render() == '[]'
modified:tests/test_inheritance.py+15 added-2 removed
4 unmodified lines
56 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""9from jinja import Environment, DictLoader101011LAYOUTTEMPLATE = '''\12|{% block block1 %}block 1 from layout{% endblock %}13|{% block block2 %}block 2 from layout{% endblock %}14|{% block block3 %}
19 unmodified lines
34{% extends "level3" %}35{% block block3 %}block 3 from level4{% endblock %}36'''373838def test_layout(env):39 tmpl = env.get_template('layout')40 assert tmpl.render() == ('|block 1 from layout|block 2 from '41 'layout|nested block 4 from layout|')
20 unmodified lines
62def test_level4(env):63 tmpl = env.get_template('level4')64 assert tmpl.render() == ('|block 1 from level1|block 5 from '65 'level3|block 3 from level4|')666768def test_super():69 env = Environment(loader=DictLoader({70 'a': '{% block intro %}INTRO{% endblock %}|'71 'BEFORE|{% block data %}INNER{% endblock %}|AFTER',72 'b': '{% extends "a" %}{% block data %}({{ '73 'super() }}){% endblock %}',74 'c': '{% extends "b" %}{% block intro %}--{{ '75 'super() }}--{% endblock %}\n{% block data '76 '%}[{{ super() }}]{% endblock %}'77 }))78 tmpl = env.get_template('c')79 assert tmpl.render() == '--INTRO--|BEFORE|[(INNER)]|AFTER'
added:tests/test_lexer.py+31 added
1# -*- coding: utf-8 -*-2"""3 unit test for the lexer4 ~~~~~~~~~~~~~~~~~~~~~~~56 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""910BALANCING = '''{% for item in seq %}${{'foo': item}|upper}{% endfor %}'''11COMMENTS = '''\12<ul>13<!--- for item in seq -->14 <li>{item}</li>15<!--- endfor -->16</ul>'''171819def test_balancing():20 from jinja import Environment21 env = Environment('{%', '%}', '${', '}')22 tmpl = env.from_string(BALANCING)23 assert tmpl.render(seq=range(3)) == "{'FOO': 0}{'FOO': 1}{'FOO': 2}"242526def test_comments():27 from jinja import Environment28 env = Environment('<!--', '-->', '{', '}')29 tmpl = env.from_string(COMMENTS)30 assert tmpl.render(seq=range(3)) == ("<ul>\n <li>0</li>\n "31 "<li>1</li>\n <li>2</li>\n</ul>")
modified:CHANGES+18 added
11 unmodified lines
1213- ``{{ debug() }}`` can now be used to get a list of filters and14 tags.1516- the template lexer keeps not track of brace, parenthesis and17 bracket balance in order to not break variable tags apart if they18 are configured to look like this: ``${expr}``. This also fixes19 the problem with nested dicts in variable expressions.2021- added whitespace management system for the template designer.2223- some small bugfixes.24
4 unmodified lines
29- strings without unicode characters are processed as binary strings now30 to workaround problems with `datetime.strftime` which only accepts31 binary strings.3233- it's now possible to use newlines in string literals3435- developer friendly traceback is now toggleable3637- silent variable name failure is now toggleable38
13 unmodified lines
52- added `sum`, `abs` and `round` filters. This fixes #2385354- added `striptags` and `xmlattr` filters for easier SGML/XML processing5556- the trans tag does not need explicit naming for variables with the same57 name any more. You can now use ``{% trans foo %}`` instead of the verbose58 version ``{% trans foo=foo %}``.5960- reimplemented Buffet plugin so that it works at least for pylons6162- added `Environment.get_translations_for_string`6364- fixed a bug in the parser that didn't unescape keyword arguments. (thanks65 to Alexey Melchakov for reporting)666768Version 1.069-----------70(released Mar 23, 2007)71
1 unmodified line
modified:setup.py+4 added
45 unmodified lines
46 ('docs', list(list_files('docs/build'))),47 ('docs/txt', list(list_files('docs/src')))48 ],49 platforms = 'any',50 entry_points='''51 [python.templating.engines]52 jinja = jinja.plugin:BuffetPlugin53 ''',54 extras_require = {'plugin': ['setuptools>=0.6a2']}55)