Skip to content
Myr

[svn] moved some of the documentation into docstrings

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 1f57be8 · Browse files · 13 files+358 added−135 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+358 added−135 removed

  • other:+358 added−135 removed

13 files+358 added−135 removed

modified:docs/src/devintro.txt+2 added-62 removed
25 unmodified lines
2627The Environment28===============2930The core component of Jinja is the `Environment`. It contains important shared31variables like configuration, filters, tests, globals and other stuff.30[[environment_doc]]3133Here the possible initialization parameters:3435========================= ==================================================36`block_start_string` * the string marking the begin of a block. this37 defaults to ``'{%'``.38`block_end_string` * the string marking the end of a block. defaults39 to ``'%}'``.40`variable_start_string` * the string marking the begin of a print41 statement. defaults to ``'{{'``.42`comment_start_string` * the string marking the begin of a43 comment. defaults to ``'{#'``.44`comment_end_string` * the string marking the end of a comment.45 defaults to ``'#}'``.46`trim_blocks` * If this is set to ``True`` the first newline47 after a block is removed (block, not48 variable tag!). Defaults to ``False``.49`auto_escape` If this is set to ``True`` Jinja will50 automatically escape all variables using xml51 escaping methods. If you don't want to escape a52 string you have to wrap it in a ``Markup``53 object from the ``jinja.datastructure`` module.54 If `auto_escape` is ``True`` there will be also55 a ``Markup`` object in the template namespace56 to define partial html fragments. Note that we do57 not recomment this feature, see also the comment58 below.59`default_filters` list of tuples in the form (``filter_name``,60 ``arguments``) where ``filter_name`` is the61 name of a registered filter and ``arguments``62 a tuple with the filter arguments. The filters63 specified here will always be applied when64 printing data to the template.65 *new in jinja 1.1*66`template_charset` The charset of the templates. Defaults67 to ``'utf-8'``.68`charset` Charset of all string input data. Defaults69 to ``'utf-8'``.70`namespace` Global namespace for all templates.71`loader` Specify a template loader.72`filters` dict of filters or the default filters if not73 defined.74`tests` dict of tests of the default tests if not defined.75`context_class` the context class this template should use. See76 the `context documentation`_ for more details.77`silent` set this to `False` if you want to receive errors78 for missing template variables or attributes.79 Defaults to `False`. *new in Jinja 1.1*80`friendly_traceback` Set this to `False` to disable the developer81 friendly traceback rewriting. Whenever an82 runtime or syntax error occours jinja will try83 to make a developer friendly traceback that shows84 the error in the template line. This however can85 be annoying when debugging broken functions which86 are called from the template. *new in Jinja 1.1*87========================= ==================================================8889All of these variables except those marked with a star (*) are modifiable after90environment initialization.9132The environment provides the following useful functions and properties in33addition to the initialization values:3435=========================== ==================================================
77 unmodified lines
113114115.. _installation: installation.txt116.. _context documentation: contextenv.txt177.. _translators: translators.txt117.. _loader: loaders.txt118.. _translators: translators.txt119.. _filter development: filters.txt120.. _test development: tests.txt
modified:docs/generate.py+10 added-1 removed
99 unmodified lines
100 result.append('`%s`\n%s' % (loader.__name__, '\n'.join(doclines)))101102 return '\n\n'.join(result)103104def generate_environment_doc():105 from jinja.environment import Environment106 return '%s\n\n%s' % (107 inspect.getdoc(Environment),108 inspect.getdoc(Environment.__init__)109 )110111e = Environment()112113PYGMENTS_FORMATTER = HtmlFormatter(style='pastie', cssclass='syntax')114115LIST_OF_FILTERS = generate_list_of_filters()116LIST_OF_TESTS = generate_list_of_tests()117LIST_OF_LOADERS = generate_list_of_loaders()118ENVIRONMENT_DOC = generate_environment_doc()119120FULL_TEMPLATE = e.from_string('''\121<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"122 "http://www.w3.org/TR/html4/strict.dtd">
113 unmodified lines
236def generate_documentation(data, link_style):237 writer = DocumentationWriter(link_style)238 data = data.replace('[[list_of_filters]]', LIST_OF_FILTERS)\239 .replace('[[list_of_tests]]', LIST_OF_TESTS)\232 .replace('[[list_of_loaders]]', LIST_OF_LOADERS)240 .replace('[[list_of_loaders]]', LIST_OF_LOADERS)\241 .replace('[[environment_doc]]', ENVIRONMENT_DOC)242 parts = publish_parts(243 data,244 writer=writer,245 settings_overrides={
50 unmodified lines
modified:jinja/translators/__init__.py+1 added-2 removed
1 unmodified line
2"""3 jinja.translators4 ~~~~~~~~~~~~~~~~~56 The submodules of this module provide translators for the jinja ast7 which basically just is the python ast with a few more nodes.6 The submodules of this module provide translators for the jinja ast.78 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""
19 unmodified lines
modified:jinja/translators/python.py+67 added-16 removed
3 unmodified lines
4 ~~~~~~~~~~~~~~~~~~~~~~~~56 This module translates a jinja ast into python code.78 This translator tries hard to keep Jinja sandboxed. All security9 relevant calls are wrapped by methods defined in the environment.10 This affects:1112 - method calls13 - attribute access14 - name resolution1516 It also adds debug symbols used by the traceback toolkit implemented17 in `jinja.utils`.1819 :copyright: 2007 by Armin Ronacher.20 :license: BSD, see LICENSE for more details.21"""22import re
95 unmodified lines
118 def __init__(self, environment, node):119 self.environment = environment120 self.node = node121122 #: mapping to constants in the environment that are not123 #: converted to context lookups. this should improve124 #: performance and avoid accidentally screwing things up125 #: by rebinding essential constants.126 self.constants = {127 'true': 'True',128 'false': 'False',129 'none': 'None',130 'undefined': 'Undefined'131 }132133 #: bind the nodes to the callback functions. There are134 #: some missing! A few are specified in the `unhandled`135 #: mapping in order to disallow their usage, some of them136 #: will not appear in the jinja parser output because137 #: they are filtered out.138 self.handlers = {139 # jinja nodes140 nodes.Template: self.handle_template,141 nodes.Text: self.handle_template_text,
7 unmodified lines
149 nodes.Filter: self.handle_filter,150 nodes.Block: self.handle_block,151 nodes.Include: self.handle_include,152 nodes.Trans: self.handle_trans,133 # used python nodes153 # python nodes154 ast.Name: self.handle_name,155 ast.AssName: self.handle_name,156 ast.Compare: self.handle_compare,157 ast.Const: self.handle_const,
19 unmodified lines
177 ast.Slice: self.handle_slice,178 ast.Sliceobj: self.handle_sliceobj179 }180181 #: mapping of unsupported syntax elements.182 #: the value represents the feature name that appears183 #: in the exception.184 self.unsupported = {185 ast.ListComp: 'list comprehensions',186 ast.From: 'imports',187 ast.Import: 'imports',188 }189190 #: because of python2.3 compatibility add generator191 #: expressions only to the list of unused features192 #: if it exists.193 if hasattr(ast, 'GenExpr'):194 self.unsupported.update({195 ast.GenExpr: 'generator expressions'196 })197171 self.require_translations = False172198 # -- public methods199200 def process(environment, node):201 """202 The only public method. Creates a translator instance,203 translates the code and returns it in form of an204 `Template` instance.205 """206 translator = PythonTranslator(environment, node)207 filename = node.filename or '<template>'208 source = translator.translate()179 return Template(environment,180 compile(source, filename, 'exec'))209 return Template(environment, compile(source, filename, 'exec'))210 process = staticmethod(process)211212 # -- private helper methods213214 def indent(self, text):215 """187 Indent the current text.216 Indent the current text. This does only indent the217 first line.218 """219 return (' ' * (self.indention * 4)) + text220221 def nodeinfo(self, node, force=False):
43 unmodified lines
265 return 'apply_filters(%s, context, %s)' % (s, _to_tuple(filters))266267 def handle_node(self, node):268 """239 Handle one node269 Handle one node. Resolves the correct callback functions defined270 in the callback mapping. This also raises the `TemplateSyntaxError`271 for unsupported syntax elements such as list comprehensions.272 """273 if node.__class__ in self.handlers:274 out = self.handlers[node.__class__](node)275 elif node.__class__ in self.unsupported:
4 unmodified lines
280 raise AssertionError('unhandled node %r' % node.__class__)281 return out282283 def reset(self):284 """285 Reset translation variables such as indention, cycle id286 or the require_translations flag.287 """288 self.indention = 0289 self.last_cycle_id = 0290 self.require_translations = False291292 def translate(self):293 """294 Translate the node defined in the constructor after295 resetting the translator.296 """297 self.reset()298 return self.handle_node(self.node)299300 # -- jinja nodes
116 unmodified lines
417 dict_lines.append(' %r: %s' % (418 str(name),419 _to_tuple(tmp)420 ))421422 # blocks must always be defined. even if it's empty. some423 # features depend on it424 lines.append('\nblocks = {\n%s\n}' % ',\n'.join(dict_lines))425426 # now get the real source lines and map the debugging symbols427 debug_mapping = []
54 unmodified lines
482 )483484 # simple loops485 else:442 write('context[\'loop\'] = loop = LoopContext(%s, context[\'loop\'], None)' %443 self.handle_node(node.seq))486 write('context[\'loop\'] = loop = LoopContext(%s, '487 'context[\'loop\'], None)' % self.handle_node(node.seq))488 write('for %s in loop:' %489 self.handle_node(node.item)490 )491
20 unmodified lines
512 write('if False:')513 self.indention += 1514 write('yield None')515 self.indention -= 2472 write('context[\'loop\'] = LoopContext(None, context[\'loop\'], buffereater(forloop))')516 write('context[\'loop\'] = LoopContext(None, context[\'loop\'], '517 'buffereater(forloop))')518 write('for item in forloop(%s):' % self.handle_node(node.seq))519 self.indention += 1520 write('yield item')521 self.indention -= 1
48 unmodified lines
570 hardcoded = False571 self.indention -= 1572573 if hardcoded:529 write('yield finish_var(context.current[%r].cycle(), context)' % name)574 write('yield finish_var(context.current[%r].cycle(), '575 'context)' % name)576 else:531 write('yield finish_var(context.current[%r].cycle(%s), context)' % (577 write('yield finish_var(context.current[%r].cycle(%s), '578 'context)' % (579 name,580 self.handle_node(node.seq)581 ))582
21 unmodified lines
604 if node.arguments:605 write('argcount = len(args)')606 tmp = []607 for idx, (name, n) in enumerate(node.arguments):561 tmp.append('\'%s\': (argcount > %d and (args[%d],) or (%s,))[0]' % (608 tmp.append('\'%s\': (argcount > %d and (args[%d],) '609 'or (%s,))[0]' % (610 name,611 idx,612 idx,613 n is None and 'Undefined' or self.handle_node(n)
8 unmodified lines
622 write('if False:')623 self.indention += 1624 write('yield False')625 self.indention -= 2578 buf.append(self.indent('context[%r] = buffereater(macro)' % node.name))626 buf.append(self.indent('context[%r] = buffereater(macro)' %627 node.name))628629 return '\n'.join(buf)630631 def handle_set(self, node):
21 unmodified lines
653 write('if False:')654 self.indention += 1655 write('yield None')656 self.indention -= 2608 write('yield %s' % self.filter('u\'\'.join(filtered())', node.filters))657 write('yield %s' % self.filter('u\'\'.join(filtered())',658 node.filters))659 return '\n'.join(buf)660661 def handle_block(self, node, level=0):662 """
176 unmodified lines
839 kwargs[arg.name] = self.handle_node(arg.expr)840 else:841 args.append(self.handle_node(arg))842 if not (args or kwargs or star_args or dstar_args):793 return 'call_function_simple(%s, context)' % self.handle_node(node.node)843 return 'call_function_simple(%s, context)' % \844 self.handle_node(node.node)845 return 'call_function(%s, context, %s, {%s}, %s, %s)' % (846 self.handle_node(node.node),847 _to_tuple(args),848 ', '.join(['%r: %s' % i for i in kwargs.iteritems()]),
138 unmodified lines
modified:jinja/datastructure.py+72 added-20 removed
42 unmodified lines
43 """44 __slots__ = ()4546 def __init__(self):47 try:48 Undefined49 except NameError:50 pass51 else:52 raise TypeError('cannot create %r instances' %53 self.__class__.__name__)47 raise TypeError('cannot create %r instances' %48 self.__class__.__name__)4950 def __add__(self, other):51 """Any operator returns the operand."""52 return other55 __sub__ = __mul__ = __div__ = __rsub__ = __rmul__ = __div__ = __radd__ = \56 __add__ = lambda self, other: other53 __sub__ = __mul__ = __div__ = __rsub__ = __rmul__ = __div__ = __mod__ =\54 __radd__ = __rmod__ = __add__5556 def __getitem__(self, arg):57 """Getting any item returns `Undefined`"""58 return self5960 def __iter__(self):61 """Iterating over `Undefined` returns an empty iterator."""62 if False:63 yield None6465 def __getattr__(self, arg):66 """Getting any attribute returns `Undefined`"""67 return self6869 def __nonzero__(self):70 """`Undefined` is considered boolean `False`"""71 return False7273 def __len__(self):74 """`Undefined` is an empty sequence"""75 return 07677 def __str__(self):78 """The string representation is empty."""79 return ''8081 def __unicode__(self):82 """The unicode representation is empty."""83 return u''8485 def __repr__(self):86 """The representation is ``'Undefined'``"""87 return 'Undefined'8889 def __int__(self):90 """Converting `Undefined` to an integer ends up in ``0``"""91 return 09293 def __float__(self):94 """Converting `Undefined` to an float ends up in ``0.0``"""95 return 0.09697 def __eq__(self, other):98 """`Undefined` is not equal to anything else."""99 return False100101 def __ne__(self, other):102 """`Undefined` is not equal to anything else."""103 return True104105 def __call__(self, *args, **kwargs):106 """Calling `Undefined` returns `Undefined`"""107 return self108109 def __copy__(self):110 """Return a copy."""111 return self11296Undefined = UndefinedType()113 def __deepcopy__(self, memo):114 """Return a deepcopy."""115 return self116117 def __reduce__(self):118 """Helper for pickle."""119 return 'Undefined'120121122#: the singleton instance of UndefinedType123Undefined = object.__new__(UndefinedType)124125126class FakeTranslator(object):127 """128 Default null translator.129 """130131 def gettext(self, s):132 """133 Translate a singular string.134 """135 return s136137 def ngettext(self, s, p, n):138 """139 Translate a plural string.140 """141 if n == 1:142 return s143 return p144
40 unmodified lines
185 # cache object used for filters and tests186 self.cache = {}187188 def pop(self):156 """Pop the last layer from the stack and return it."""189 """190 Pop the last layer from the stack and return it.191 """192 rv = self._stack.pop()193 self.current = self._stack[-1]194 return rv195196 def push(self, data=None):162 """Push a new dict or empty layer to the stack and return that layer"""197 """198 Push a new dict or empty layer to the stack and return that layer199 """200 data = data or {}201 self._stack.append(data)202 self.current = self._stack[-1]203 return data204205 def to_dict(self):169 """Convert the context into a dict. This skips the globals."""206 """207 Convert the context into a dict. This skips the globals.208 """209 result = {}210 for layer in self._stack[1:]:211 for key, value in layer.iteritems():212 if key.startswith('::'):
1 unmodified line
214 result[key] = value215 return result216217 def __getitem__(self, name):218 """219 Resolve one item. Restrict the access to internal variables220 such as ``'::cycle1'``. Resolve deferreds.221 """222 if not name.startswith('::'):223 # because the stack is usually quite small we better use [::-1]224 # which is faster than reversed() somehow.225 for d in self._stack[::-1]:
11 unmodified lines
237 return Undefined238 raise TemplateRuntimeError('%r is not defined' % name)239240 def __setitem__(self, name, value):241 """242 Set a variable in the outermost layer.243 """244 self.current[name] = value245246 def __delitem__(self, name):247 """248 Delete an variable in the outermost layer.249 """250 if name in self.current:251 del self.current[name]252253 def __contains__(self, name):254 """255 Check if the context contains a given variable.256 """257 for layer in self._stack:258 if name in layer:259 return True260 return False261262 def __repr__(self):211 tmp = {}212 for d in self._stack:213 for key, value in d.iteritems():214 tmp[key] = value215 return 'Context(%s)' % repr(tmp)263 """264 String representation of the context.265 """266 return 'Context(%r)' % self.to_dict()267268269class LoopContext(object):270 """
128 unmodified lines
399 it supports pushing tokens back to the stream.400 """401402 def __init__(self, generator):352 self._generator = generator403 self._next = generator.next404 self._pushed = []405 self.last = (1, 'initial', '')406407 def __iter__(self):408 """Return self in order to mark this is iterator."""409 return self410411 def __nonzero__(self):412 """Are we at the end of the tokenstream?"""
11 unmodified lines
424 """Return the next token from the stream."""425 if self._pushed:426 rv = self._pushed.pop()427 else:376 rv = self._generator.next()428 rv = self._next()429 self.last = rv430 return rv431432 def look(self):
28 unmodified lines
modified:jinja/defaults.py+3 added
12 unmodified lines
13from jinja.utils import debug_context, safe_range, generate_lorem_ipsum, \14 watch_changes151617__all__ = ['DEFAULT_FILTERS', 'DEFAULT_TESTS', 'DEFAULT_NAMESPACE']181920DEFAULT_NAMESPACE = {21 'range': safe_range,22 'debug': debug_context,23 'lipsum': generate_lorem_ipsum,
2 unmodified lines
modified:jinja/environment.py+88 added-5 removed
17 unmodified lines
18 SecurityException, TemplateSyntaxError, TemplateRuntimeError19from jinja.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE202122__all__ = ['Environment']232425class Environment(object):26 """27 The jinja environment.2829 The core component of Jinja is the `Environment`. It contains30 important shared variables like configuration, filters, tests,31 globals and others.32 """3334 def __init__(self,35 block_start_string='{%',
13 unmodified lines
49 tests=None,50 context_class=Context,51 silent=True,52 friendly_traceback=True):53 """54 Here the possible initialization parameters:5556 ========================= ============================================57 `block_start_string` * the string marking the begin of a block.58 this defaults to ``'{%'``.59 `block_end_string` * the string marking the end of a block.60 defaults to ``'%}'``.61 `variable_start_string` * the string marking the begin of a print62 statement. defaults to ``'{{'``.63 `comment_start_string` * the string marking the begin of a64 comment. defaults to ``'{#'``.65 `comment_end_string` * the string marking the end of a comment.66 defaults to ``'#}'``.67 `trim_blocks` * If this is set to ``True`` the first newline68 after a block is removed (block, not69 variable tag!). Defaults to ``False``.70 `auto_escape` If this is set to ``True`` Jinja will71 automatically escape all variables using xml72 escaping methods. If you don't want to73 escape a string you have to wrap it in a74 ``Markup`` object from the75 ``jinja.datastructure`` module. If76 `auto_escape` is ``True`` there will be also77 a ``Markup`` object in the template78 namespace to define partial html fragments.79 Note that we do not recomment this feature.80 `default_filters` list of tuples in the form (``filter_name``,81 ``arguments``) where ``filter_name`` is the82 name of a registered filter and83 ``arguments`` a tuple with the filter84 arguments. The filters specified here will85 always be applied when printing data to the86 template. *new in Jinja 1.1*87 `template_charset` The charset of the templates. Defaults88 to ``'utf-8'``.89 `charset` Charset of all string input data. Defaults90 to ``'utf-8'``.91 `namespace` Global namespace for all templates.92 `loader` Specify a template loader.93 `filters` dict of filters or the default filters if94 not defined.95 `tests` dict of tests of the default tests if not96 defined.97 `context_class` the context class this template should use.98 See the `Context` documentation for more99 details.100 `silent` set this to `False` if you want to receive101 errors for missing template variables or102 attributes. Defaults to `False`. *new in103 Jinja 1.1*104 `friendly_traceback` Set this to `False` to disable the developer105 friendly traceback rewriting. Whenever an106 runtime or syntax error occours jinja will107 try to make a developer friendly traceback108 that shows the error in the template line.109 This however can be annoying when debugging110 broken functions that are called from the111 template. *new in Jinja 1.1*112 ========================= ============================================113114 All of these variables except those marked with a star (*) are115 modifiable after environment initialization.116 """117118 # lexer / parser information119 self.block_start_string = block_start_string120 self.block_end_string = block_end_string121 self.variable_start_string = variable_start_string
29 unmodified lines
151 """152 Get or set the template loader.153 """154 self._loader = LoaderWrapper(self, value)84 loader = property(lambda s: s._loader, loader, loader.__doc__)155 loader = property(lambda s: s._loader, loader, doc=loader.__doc__)156157 def parse(self, source, filename=None):87 """Function that creates a new parser and parses the source."""158 """159 Parse the sourcecode and return the abstract syntax tree. This tree160 of nodes is used by the `translators`_ to convert the template into161 executable source- or bytecode.162163 .. _translators: translators.txt164 """165 parser = Parser(self, source, filename)166 return parser.parse()167168 def from_string(self, source):92 """Load a template from a string."""169 """170 Load and parse a template source and translate it into eval-able171 Python code. This code is wrapped within a `Template` class that172 allows you to render it.173 """174 from jinja.parser import Parser175 from jinja.translators.python import PythonTranslator176 try:177 rv = PythonTranslator.process(self, Parser(self, source).parse())
10 unmodified lines
188 rv._source = source189 return rv190191 def get_template(self, filename):111 """Load a template from a filename. Only works112 if a proper loader is set."""192 """193 Load a template from a loader. If the template does not exist, you194 will get a `TemplateNotFound` exception.195 """196 return self._loader.load(filename)197198 def to_unicode(self, value):199 """
127 unmodified lines
modified:jinja/filters.py+11 added-5 removed
267 unmodified lines
268 def wrapped(env, context, seq):269 try:270 return iter(seq).next()271 except StopIteration:272 if env.silent:272 return Undefined273 return Undefined274 raise TemplateRuntimeError('%r is empty' % seq)275 return wrapped276277278def do_last():
2 unmodified lines
281 """282 def wrapped(env, context, seq):283 try:284 return iter(_reversed(seq)).next()283 except (TypeError, StopIteration):284 return Undefined285 except StopIteration:286 if env.silent:287 return Undefined288 raise TemplateRuntimeError('%r is empty' % seq)289 return wrapped290291292def do_random():
2 unmodified lines
295 """296 def wrapped(env, context, seq):297 try:298 return choice(seq)295 except:296 return Undefined299 except IndexError:300 if env.silent:301 return Undefined302 raise TemplateRuntimeError('%r is empty' % seq)303 return wrapped304305306def do_urlencode():
350 unmodified lines
modified:jinja/lexer.py+22 added-3 removed
1 unmodified line
2"""3 jinja.lexer4 ~~~~~~~~~~~56 This module implements a Jinja / Python combination lexer. The7 `Lexer` class provided by this module is used to do some preprocessing8 for Jinja.910 On the one hand it filters out invalid operators like the bitshift11 operators we don't allow in templates. On the other hand it separates12 template code and python code in expressions.1314 Because of some limitations in the compiler package which are just15 natural but annoying for Jinja, the lexer also "escapes" non names that16 are not keywords. The Jinja parser then removes those escaping marks17 again.1819 This is required in order to make "class" and some other python keywords20 we don't use valid identifiers.2122 :copyright: 2007 by Armin Ronacher.23 :license: BSD, see LICENSE for more details.24"""25import re
5 unmodified lines
31except NameError:32 from sets import Set as set333435__all__ = ['Lexer', 'Failure', 'keywords']363738# static regular expressions39whitespace_re = re.compile(r'\s+(?m)')40name_re = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*')41string_re = re.compile(r"('([^'\\]*(?:\\.[^'\\]*)*)'"
131 unmodified lines
173 back to the stream. That's for example done by the parser.174175 Additionally non keywords are escaped.176 """158 def filter():177 def generate():178 for lineno, token, value in self.tokeniter(source):179 if token == 'name' and value not in keywords:180 value += '_'181 yield lineno, token, value163 return TokenStream(filter())182 return TokenStream(generate())183184 def tokeniter(self, source):185 """186 This method tokenizes the text and returns the tokens in a generator.
1 unmodified line
188 you get is not compatible with the input the jinja parser wants. The189 parser uses the `tokenize` function with returns a `TokenStream` with190 some escaped tokens.191 """173 source = type(source)('\n').join(source.splitlines())192 source = '\n'.join(source.splitlines())193 pos = 0194 lineno = 1195 stack = ['root']196 statetokens = self.rules['root']
89 unmodified lines
modified:jinja/nodes.py+5 added-1 removed
1 unmodified line
2"""3 jinja.nodes4 ~~~~~~~~~~~56 Additional nodes for Jinja. Look like nodes from the ast.6 This module implements additional nodes derived from the ast base node.78 It also provides some node tree helper functions like `in_lineno` and9 `get_nodes` used by the parser and translator in order to normalize10 python and jinja nodes.1112 :copyright: 2007 by Armin Ronacher.13 :license: BSD, see LICENSE for more details.14"""15from compiler import ast
338 unmodified lines
modified:jinja/parser.py+12 added-18 removed
3 unmodified lines
4 ~~~~~~~~~~~~56 Implements the template parser.78 The Jinja template parser is not a real parser but a combination of the9 python compiler package and some postprocessing. The tokens yielded by10 the lexer are used to separate template data and expressions. The11 expression tokens are then converted into strings again and processed12 by the python parser.1314 :copyright: 2007 by Armin Ronacher.15 :license: BSD, see LICENSE for more details.16"""17import re
7 unmodified lines
25except NameError:26 from sets import Set as set272829__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'
6 unmodified lines
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'444537string_inc_re = re.compile(r'(?:[^\d]*(\d+)[^\d]*)+')383940def inc_string(s):41 """42 Increment a string43 """44 m = string_inc_re.search(s)45 if m:46 next = str(int(m.group(1)) + 1)47 start, end = m.span(1)48 s = s[:max(end - len(next), start)] + next + s[end:]49 else:50 name, ext = s.rsplit('.', 1)51 return '%s2.%s' % (name, ext)52 return s535446class Parser(object):47 """48 The template parser class.49
7 unmodified lines
57 self.source = source58 self.filename = filename59 self.tokenstream = environment.lexer.tokenize(source)6061 #: if this template has a parent template it's stored here62 #: after parsing63 self.extends = None64 #: set for blocks in order to keep them unique65 self.blocks = set()6667 self.directives = {68 'raw': self.handle_raw_directive,
569 unmodified lines
modified:jinja/utils.py+58 added-1 removed
19 unmodified lines
20from jinja.nodes import Trans21from jinja.datastructure import Context, TemplateData22from jinja.exceptions import SecurityException, TemplateNotFound2324#: the python2.4 version of deque is missing the remove method25#: because a for loop with a lookup for the missing value written26#: in python is slower we just use deque if we have python2.5 or higher27if sys.version_info >= (2, 5):28 from collections import deque29else:30 deque = None
287 unmodified lines
318319320def collect_translations(ast):321 """319 Collect all translatable strings for the given ast.322 Collect all translatable strings for the given ast. The323 return value is a list of tuples in the form ``(lineno, singular,324 plural)``. If a translation doesn't require a plural form the325 third item is `None`.326 """327 todo = [ast]328 result = []329 while todo:
103 unmodified lines
433 self._remove = self._queue.remove434 self._append = self._queue.append435436 def copy(self):437 """438 Return an shallow copy of the instance.439 """440 rv = CacheDict(self.capacity)441 rv._mapping.update(self._mapping)442 rv._queue = self._queue[:]443 return rv444445 def get(self, key, default=None):446 """447 Return an item from the cache dict or `default`448 """449 if key in self:450 return self[key]451 return default452453 def setdefault(self, key, default=None):454 """455 Set `default` if the key is not in the cache otherwise456 leave unchanged. Return the value of this key.457 """458 if key in self:459 return self[key]460 self[key] = default461 return default462463 def clear(self):464 """465 Clear the cache dict.466 """467 self._mapping.clear()468 try:469 self._queue.clear()470 except AttributeError:471 del self._queue[:]472473 def __contains__(self, key):474 """475 Check if a key exists in this cache dict.476 """477 return key in self._mapping478479 def __len__(self):480 """481 Return the current size of the cache dict.482 """483 return len(self._mapping)484485 def __repr__(self):486 return '<%s %r>' % (
1 unmodified line
488 self._mapping489 )490491 def __getitem__(self, key):492 """493 Get an item from the cache dict. Moves the item up so that494 it has the highest priority then.495496 Raise an `KeyError` if it does not exist.497 """498 rv = self._mapping[key]499 if self._queue[-1] != key:500 self._remove(key)501 self._append(key)502 return rv503504 def __setitem__(self, key, value):505 """506 Sets the value for an item. Moves the item up so that it507 has the highest priority then.508 """509 if key in self._mapping:510 self._remove(key)511 elif len(self._mapping) == self.capacity:512 del self._mapping[self._popleft()]513 self._append(key)514 self._mapping[key] = value515516 def __delitem__(self, key):517 """518 Remove an item from the cache dict.519 Raise an `KeyError` if it does not exist.520 """521 del self._mapping[key]522 self._remove(key)523524 def __iter__(self):525 """526 Iterate over all values in the cache dict, ordered by527 the most recent usage.528 """529 try:530 return reversed(self._queue)531 except NameError:532 return iter(self._queue[::-1])533534 def __reversed__(self):535 """536 Iterate over the values in the cache dict, oldest items537 coming first.538 """539 return iter(self._queue)540541 __copy__ = copy542543 def __deepcopy__(self):544 """545 Return a deep copy of the cache dict.546 """547 from copy import deepcopy548 rv = CacheDict(self.capacity)549 rv._mapping = deepcopy(self._mapping)550 rv._queue = deepcopy(self._queue)551 return rv
modified:CHANGES+7 added-1 removed
13 unmodified lines
14- some small bugfixes.1516- improved security system regarding function calls.1718- added `lipsum` function18- added `lipsum` function to generate random text.1920- strings without unicode characters are processed as binary strings now21 to workaround problems with `datetime.strftime` which only accepts22 binary strings.
1 unmodified line
24- developer friendly traceback is now toggleable2526- silent variable name failure is now toggleable2728- fixed issue with old-style classes not implementing `__getitem__`29 (thanks to Axel Böhm for discovering that bug)3031- added a bunch of new docstrings to the Jinja classes. Makes fun now to32 use pydoc :-)333435Version 1.036-----------37(released Mar 23, 2007)38
1 unmodified line