Skip to content
Myr

end of line sequence is no configurable

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 5c047ea · Browse files · 7 files+83 added−50 removed
This commit

State

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

Diff stats

7 files+83 added−50 removed

  • other:+83 added−50 removed

7 files+83 added−50 removed

modified:docs/api.rst+30 added
42 unmodified lines
4344 print template.render(the='variables', go='here')454647Unicode48-------4950Jinja2 is using unicode internally which means that you have to pass unicode51objects to the render function or bytestrings that only consist of ASCII52characters. Additionally newlines are normalized to one end of line53sequence which is per default UNIX style (``\n``).545556High Level API57--------------5859.. autoclass:: jinja2.environment.Environment([options])
209 unmodified lines
269.. autoexception:: jinja2.exceptions.TemplateNotFound270271.. autoexception:: jinja2.exceptions.TemplateSyntaxError272273 .. attribute:: message274275 The error message as utf-8 bytestring.276277 .. attribute:: lineno278279 The line number where the error occurred280281 .. attribute:: name282283 The load name for the template as unicode string.284285 .. attribute:: filename286287 The filename that loaded the template as bytestring in the encoding288 of the file system (most likely utf-8 or mbcs on Windows systems).289290 The reason why the filename and error message are bytestrings and not291 unicode strings is that Python 2.x is not using unicode for exceptions292 and tracebacks as well as the compiler. This will change with Python 3.293294.. autoexception:: jinja2.exceptions.TemplateAssertionError295296297.. _writing-filters:
104 unmodified lines
modified:jinja2/compiler.py-1 removed
39 unmodified lines
40def generate(node, environment, name, filename, stream=None):41 """Generate the python source for a node tree."""42 if not isinstance(node, nodes.Template):43 raise TypeError('Can\'t compile non template nodes')44 node.freeze()44 generator = CodeGenerator(environment, name, filename, stream)45 generator.visit(node)46 if stream is None:47 return generator.stream.getvalue()
1334 unmodified lines
modified:jinja2/environment.py+16 added-4 removed
66 unmodified lines
67 assert environment.block_start_string != \68 environment.variable_start_string != \69 environment.comment_start_string, 'block, variable and comment ' \70 'start strings must be different'71 assert environment.newline_sequence in ('\r', '\r\n', '\n'), \72 'newline_sequence set to unknown line ending string.'73 return environment747576class Environment(object):75 """The core component of Jinja is the `Environment`. It contains77 r"""The core component of Jinja is the `Environment`. It contains78 important shared variables like configuration, filters, tests,79 globals and others. Instances of this class may be modified if80 they are not shared and if no template was loaded so far.81 Modifications on environments after the first template was loaded
28 unmodified lines
110 `trim_blocks`111 If this is set to ``True`` the first newline after a block is112 removed (block, not variable tag!). Defaults to `False`.113114 `newline_sequence`115 The sequence that starts a newline. Must be one of ``'\r'``,116 ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a117 useful default for Linux and OS X systems as well as web118 applications.119120 `extensions`121 List of Jinja extensions to use. This can either be import paths122 as strings or extension classes. For more information have a123 look at :ref:`the extensions documentation <jinja-extensions>`.
54 unmodified lines
178 comment_start_string=COMMENT_START_STRING,179 comment_end_string=COMMENT_END_STRING,180 line_statement_prefix=LINE_STATEMENT_PREFIX,181 trim_blocks=False,182 newline_sequence='\n',183 extensions=(),184 optimized=True,185 undefined=Undefined,186 finalize=None,
20 unmodified lines
207 self.comment_start_string = comment_start_string208 self.comment_end_string = comment_end_string209 self.line_statement_prefix = line_statement_prefix210 self.trim_blocks = trim_blocks211 self.newline_sequence = newline_sequence212213 # runtime information214 self.undefined = undefined215 self.optimized = optimized
233 unmodified lines
449 comment_start_string='{#',450 comment_end_string='#}',451 line_statement_prefix=None,452 trim_blocks=False,453 newline_sequence='\n',454 extensions=(),455 optimized=True,456 undefined=Undefined,457 finalize=None,458 autoescape=False):459 env = get_spontaneous_environment(460 block_start_string, block_end_string, variable_start_string,461 variable_end_string, comment_start_string, comment_end_string,451 line_statement_prefix, trim_blocks, tuple(extensions), optimized,452 undefined, finalize, autoescape, None, 0, False)462 line_statement_prefix, trim_blocks, newline_sequence,463 frozenset(extensions), optimized, undefined, finalize,464 autoescape, None, 0, False)465 return env.from_string(source, template_class=cls)466467 @classmethod468 def from_code(cls, environment, code, globals, uptodate=None):
83 unmodified lines
552 """This method works like the :attr:`module` attribute when called553 without arguments but it will evaluate the template every call554 rather then caching the template. It's also possible to provide555 a dict which is then used as context. The arguments are the same544 as fo the :meth:`new_context` method.556 as for the :meth:`new_context` method.557 """558 return TemplateModule(self, self.new_context(vars, shared))559560 @property
130 unmodified lines
modified:jinja2/exceptions.py+24 added-14 removed
12 unmodified lines
13class TemplateError(Exception):14 """Baseclass for all template errors."""151617class UndefinedError(TemplateError):18 """Raised if a template tries to operate on :class:`Undefined`."""192021class SecurityError(TemplateError):22 """Raised if a template tries to do something insecure if the23 sandbox is enabled.24 """252617class TemplateNotFound(IOError, LookupError, TemplateError):18 """Raised if a template does not exist."""1920 def __init__(self, name):
5 unmodified lines
26 """Raised to tell the user that there is a problem with the template."""2728 def __init__(self, message, lineno, name=None, filename=None):29 if name is not None:40 extra = '%s, line %d' % (name, lineno)30 extra = '%s, line %d' % (name.encode('utf-8'), lineno)31 else:32 extra = 'line %d' % lineno33 # if the message was provided as unicode we have to encode it34 # to utf-8 explicitly35 if isinstance(message, unicode):36 message = message.encode('utf-8')37 # otherwise make sure it's a in fact valid utf-838 else:39 message = message.decode('utf-8', 'ignore').encode('utf-8')40 TemplateError.__init__(self, '%s (%s)' % (message, extra))41 self.message = message42 self.lineno = lineno43 self.name = name
2 unmodified lines
4647class TemplateAssertionError(TemplateSyntaxError):48 """Like a template syntax error, but covers cases where something in the49 template caused an error at compile time that wasn't necessarily caused53 by a syntax error.50 by a syntax error. However it's a direct subclass of51 :exc:`TemplateSyntaxError` and has the same attributes.52 """535455class TemplateRuntimeError(TemplateError):58 """A runtime error."""56 """A generic runtime error in the template engine. Under some situations57 Jinja may raise this exception.58 """596061class FilterArgumentError(Exception):61class UndefinedError(TemplateRuntimeError):62 """Raised if a template tries to operate on :class:`Undefined`."""636465class SecurityError(TemplateRuntimeError):66 """Raised if a template tries to do something insecure if the67 sandbox is enabled.68 """697071class FilterArgumentError(TemplateRuntimeError):72 """This error is raised if a filter was called with inappropriate73 arguments74 """
modified:jinja2/ext.py+1 added-1 removed
365 unmodified lines
366 options.get('comment_start_string', '{#'),367 options.get('comment_end_string', '#}'),368 options.get('line_statement_prefix') or None,369 options.get('trim_blocks', '').lower() in ('1', 'on', 'yes', 'true'),370 tuple(extensions),370 '\n', frozenset(extensions),371 # fill with defaults so that environments are shared372 # with other spontaneus environments. The rest of the373 # arguments are optimizer, undefined, finalize, autoescape,374 # loader, cache size and auto reloading setting
12 unmodified lines
modified:jinja2/lexer.py+12 added-7 removed
31 unmodified lines
32 r'|"([^"\\]*(?:\\.[^"\\]*)*)")(?ms)')33integer_re = re.compile(r'\d+')34name_re = re.compile(r'\b[a-zA-Z_][a-zA-Z0-9_]*\b')35float_re = re.compile(r'\d+\.\d+')36newline_re = re.compile(r'(\r\n|\r|\n)')3738# bind operators to token types39operators = {40 '+': 'add',
208 unmodified lines
249 environment.variable_end_string,250 environment.comment_start_string,251 environment.comment_end_string,252 environment.line_statement_prefix,252 environment.trim_blocks)253 environment.trim_blocks,254 environment.newline_sequence)255 lexer = _lexer_cache.get(key)256 if lexer is None:257 lexer = type.__call__(cls, environment)258 _lexer_cache[key] = lexer
50 unmodified lines
309310 # block suffix if trimming is enabled311 block_suffix_re = environment.trim_blocks and '\\n?' or ''312313 self.newline_sequence = environment.newline_sequence314315 # global lexing rules316 self.rules = {317 'root': [318 # directives
49 unmodified lines
368 (c(r'\s*(\n|$)'), 'linestatement_end', '#pop')369 ] + tag_rules370 }371372 def _normalize_newlines(self, value):373 """Called for strings and template data to normlize it to unicode."""374 return newline_re.sub(self.newline_sequence, value)375376 def tokenize(self, source, name=None, filename=None):377 """Works like `tokeniter` but returns a tokenstream of tokens and not378 a generator or token tuples. Additionally all token values are already379 converted into types and postprocessed. For example comments are removed,
11 unmodified lines
391 # we are not interested in those tokens in the parser392 elif token in ('raw_begin', 'raw_end'):393 continue394 elif token == 'data':387 try:388 value = str(value)389 except UnicodeError:390 pass395 value = self._normalize_newlines(value)396 elif token == 'keyword':397 token = value398 elif token == 'name':399 value = str(value)400 elif token == 'string':401 # try to unescape string402 try:398 value = value[1:-1] \403 value = self._normalize_newlines(value[1:-1]) \404 .encode('ascii', 'backslashreplace') \405 .decode('unicode-escape')406 except Exception, e:407 msg = str(e).split(':')[-1].strip()
20 unmodified lines
428 The output you get is not compatible with the input the jinja parser429 wants. The parser uses the `tokenize` function with returns a430 `TokenStream` and postprocessed tokens.431 """427 source = u'\n'.join(unicode(source).splitlines())432 source = '\n'.join(unicode(source).splitlines())433 pos = 0434 lineno = 1435 stack = ['root']436 statetokens = self.rules['root']
119 unmodified lines
modified:jinja2/nodes.py-23 removed
82 unmodified lines
83 positional arguments, attributes as keyword arguments. Each node has84 two attributes: `lineno` (the line number of the node) and `environment`.85 The `environment` attribute is set at the end of the parsing process for86 all nodes automatically.8788 Nodes can be frozen which makes them hashable. The compiler freezes the89 nodes automatically. Modifications on frozen nodes are possible but not90 allowed.87 """88 __metaclass__ = NodeType89 fields = ()90 attributes = ('lineno', 'environment')91 abstract = True96 frozen = False9293 def __init__(self, *fields, **attributes):94 if self.abstract:95 raise TypeError('abstract nodes are not instanciable')
116 unmodified lines
212 node.environment = environment213 todo.extend(node.iter_child_nodes())214 return self215221 def freeze(self):222 """Freeze the complete node tree which makes them hashable.223 This happens automatically on compilation. Frozen nodes must not be224 modified any further. Extensions may not freeze nodes that appear225 in the final node tree (ie: nodes that are returned from the extension226 parse method).227 """228 todo = deque([self])229 while todo:230 node = todo.popleft()231 node.frozen = True232 todo.extend(node.iter_child_nodes())233216 def __eq__(self, other):217 return type(self) is type(other) and \218 tuple(self.iter_fields()) == tuple(other.iter_fields())219220 def __ne__(self, other):221 return not self.__eq__(other)222241 def __hash__(self):242 if not self.frozen:243 raise TypeError('unfrozen nodes are unhashable')244 return hash(tuple(self.iter_fields()))245223 def __repr__(self):224 return '%s(%s)' % (225 self.__class__.__name__,226 ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
570 unmodified lines