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
Provenance
- Commit
f3c35c4- Tree
560bbf5- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
5c047ea
7 files changed+83 added−50 removed
modified:docs/api.rst+30 added
42 unmodified lines43 44 print template.render(the='variables', go='here')45 46 47+Unicode48+-------49+50+Jinja2 is using unicode internally which means that you have to pass unicode51+objects to the render function or bytestrings that only consist of ASCII52+characters. Additionally newlines are normalized to one end of line53+sequence which is per default UNIX style (``\n``).54+55+56 High Level API57 --------------58 59 .. autoclass:: jinja2.environment.Environment([options])209 unmodified lines269 .. autoexception:: jinja2.exceptions.TemplateNotFound270 271 .. autoexception:: jinja2.exceptions.TemplateSyntaxError272 273+ .. attribute:: message274+275+ The error message as utf-8 bytestring.276+277+ .. attribute:: lineno278+279+ The line number where the error occurred280+281+ .. attribute:: name282+283+ The load name for the template as unicode string.284+285+ .. attribute:: filename286+287+ The filename that loaded the template as bytestring in the encoding288+ of the file system (most likely utf-8 or mbcs on Windows systems).289+290+ 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.293+294 .. autoexception:: jinja2.exceptions.TemplateAssertionError295 296 297 .. _writing-filters:104 unmodified linesmodified:jinja2/compiler.py-1 removed
39 unmodified lines40 def 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 linesmodified:jinja2/environment.py+16 added-4 removed
66 unmodified lines67 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 environment74 75 76 class 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 loaded28 unmodified lines110 `trim_blocks`111 If this is set to ``True`` the first newline after a block is112 removed (block, not variable tag!). Defaults to `False`.113 114+ `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.119+120 `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 lines178 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 lines207 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_sequence212 213 # runtime information214 self.undefined = undefined215 self.optimized = optimized233 unmodified lines449 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)466 467 @classmethod468 def from_code(cls, environment, code, globals, uptodate=None):83 unmodified lines552 """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))559 560 @property130 unmodified linesmodified:jinja2/exceptions.py+24 added-14 removed
12 unmodified lines13 class TemplateError(Exception):14 """Baseclass for all template errors."""15 16 17-class UndefinedError(TemplateError):18- """Raised if a template tries to operate on :class:`Undefined`."""19-20-21-class SecurityError(TemplateError):22- """Raised if a template tries to do something insecure if the23- sandbox is enabled.24- """25-26-17 class TemplateNotFound(IOError, LookupError, TemplateError):18 """Raised if a template does not exist."""19 20 def __init__(self, name):5 unmodified lines26 """Raised to tell the user that there is a problem with the template."""27 28 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 = name2 unmodified lines46 47 class 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 """53 54 55 class TemplateRuntimeError(TemplateError):58- """A runtime error."""56+ """A generic runtime error in the template engine. Under some situations57+ Jinja may raise this exception.58+ """59 60 61-class FilterArgumentError(Exception):61+class UndefinedError(TemplateRuntimeError):62+ """Raised if a template tries to operate on :class:`Undefined`."""63+64+65+class SecurityError(TemplateRuntimeError):66+ """Raised if a template tries to do something insecure if the67+ sandbox is enabled.68+ """69+70+71+class 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 lines366 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 setting12 unmodified linesmodified:jinja2/lexer.py+12 added-7 removed
31 unmodified lines32 r'|"([^"\\]*(?:\\.[^"\\]*)*)")(?ms)')33 integer_re = re.compile(r'\d+')34 name_re = re.compile(r'\b[a-zA-Z_][a-zA-Z0-9_]*\b')35 float_re = re.compile(r'\d+\.\d+')36+newline_re = re.compile(r'(\r\n|\r|\n)')37 38 # bind operators to token types39 operators = {40 '+': 'add',208 unmodified lines249 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] = lexer50 unmodified lines309 310 # block suffix if trimming is enabled311 block_suffix_re = environment.trim_blocks and '\\n?' or ''312 313+ self.newline_sequence = environment.newline_sequence314+315 # global lexing rules316 self.rules = {317 'root': [318 # directives49 unmodified lines368 (c(r'\s*(\n|$)'), 'linestatement_end', '#pop')369 ] + tag_rules370 }371 372+ 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)375+376 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 lines391 # 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 lines428 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 linesmodified:jinja2/nodes.py-23 removed
82 unmodified lines83 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.87-88- 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 = False92 93 def __init__(self, *fields, **attributes):94 if self.abstract:95 raise TypeError('abstract nodes are not instanciable')116 unmodified lines212 node.environment = environment213 todo.extend(node.iter_child_nodes())214 return self215 221- 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())233-216 def __eq__(self, other):217 return type(self) is type(other) and \218 tuple(self.iter_fields()) == tuple(other.iter_fields())219 220 def __ne__(self, other):221 return not self.__eq__(other)222 241- def __hash__(self):242- if not self.frozen:243- raise TypeError('unfrozen nodes are unhashable')244- return hash(tuple(self.iter_fields()))245-223 def __repr__(self):224 return '%s(%s)' % (225 self.__class__.__name__,226 ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for570 unmodified lines