A dict of filters for this environment. As long as no template was
loaded it's safe to add new filters or remove old. For custom filters
- see :ref:`writing-filters`. Unlike regular identifiers filters and
- tests may contain dots to group functions with similar functionality.
- For example `to.unicode` is a valid name for a filter.
+ see :ref:`writing-filters`. For valid filter names have a look at
+ :ref:`identifier-naming`.
.. attribute:: tests
A dict of test functions for this environment. As long as no
template was loaded it's safe to modify this dict. For custom tests
- see :ref:`writing-tests`. Unlike regular identifiers filters and
- tests may contain dots to group functions with similar functionality.
- For example `check.positive` is a valid name for a test.
+ see :ref:`writing-tests`. For valid test names have a look at
+ :ref:`identifier-naming`.
.. attribute:: globals
in a template and (if the optimizer is enabled) may not be
overridden by templates. As long as no template was loaded it's safe
to modify this dict. For more details see :ref:`global-namespace`.
+ For valid object names have a look at :ref:`identifier-naming`.
.. automethod:: overlay([options])
:members: disable_buffering, enable_buffering
+.. _identifier-naming:
+
+Notes on Identifiers
+~~~~~~~~~~~~~~~~~~~~
+
+Jinja2 uses the regular Python 2.x naming rules. Valid identifiers have to
+match ``[a-zA-Z_][a-zA-Z0-9_]*``. As a matter of fact non ASCII characters
+are currently not allowed. This limitation will probably go away as soon as
+unicode identifiers are fully specified for Python 3.
+
+Filters and tests are looked up in separate namespaces and have slightly
+modified identifier syntax. Filters and tests may contain dots to group
+filters and tests by topic. For example it's perfectly valid to add a
+function into the filter dict and call it `to.unicode`. The regular
+expression for filter and test identifiers is
+``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.
+
+
Undefined Types
---------------
:copyright: Copyright 2008 by Armin Ronacher.
:license: GNU GPL.
"""
-import string
from time import time
from copy import copy
from random import randrange
from keyword import iskeyword
from cStringIO import StringIO
-from itertools import chain, takewhile
+from itertools import chain
from jinja2 import nodes
from jinja2.visitor import NodeVisitor, NodeTransformer
from jinja2.exceptions import TemplateAssertionError
else:
have_condexpr = True
-_safe_ident_chars = set(string.letters + '0123456789')
-
def generate(node, environment, name, filename, stream=None):
"""Generate the python source for a node tree."""
return generator.stream.getvalue()
-def mask_identifier(ident):
- """Mask an identifier properly for python source code."""
- rv = ['l_']
- for char in ident:
- if char in _safe_ident_chars:
- rv.append(char)
- else:
- rv.append('_%x_' % ord(char))
- return str(''.join(rv))
-
-
-def unmask_identifier(ident):
- """Unmask an identifier."""
- if not ident.startswith('l_'):
- return ident
- rv = []
- i = iter(ident[2:])
- for c in i:
- if c == '_':
- c = unichr(int(concat(takewhile(lambda c: c != '_', i)), 16))
- rv.append(c)
- return ''.join(rv)
-
-
def has_safe_repr(value):
"""Does the node have a safe representation?"""
if value is None or value is NotImplemented or value is Ellipsis:
def pull_locals(self, frame):
"""Pull all the references identifiers into the local scope."""
for name in frame.identifiers.undeclared:
- self.writeline('%s = context.resolve(%r)' % (mask_identifier(name),
- name))
+ self.writeline('l_%s = context.resolve(%r)' % (name, name))
def pull_dependencies(self, nodes):
"""Pull all the dependencies."""
aliases = {}
for name in frame.identifiers.find_shadowed():
aliases[name] = ident = self.temporary_identifier()
- self.writeline('%s = %s' % (ident, mask_identifier(name)))
+ self.writeline('%s = l_%s' % (ident, name))
return aliases
def function_scoping(self, node, frame, children=None):
func_frame.accesses_kwargs = False
func_frame.accesses_varargs = False
func_frame.accesses_caller = False
- func_frame.arguments = args = [mask_identifier(x.name)
- for x in node.args]
+ func_frame.arguments = args = ['l_' + x.name for x in node.args]
undeclared = find_undeclared(children, ('caller', 'kwargs', 'varargs'))
def visit_Import(self, node, frame):
"""Visit regular imports."""
- self.writeline(mask_identifier(node.target) + ' = ', node)
+ self.writeline('l_%s = ' % node.target, node)
if frame.toplevel:
self.write('context.vars[%r] = ' % node.target)
self.write('environment.get_template(')
name, alias = name
else:
alias = name
- self.writeline('%s = getattr(included_template, '
- '%r, missing)' % (mask_identifier(alias), name))
- self.writeline('if %s is missing:' % mask_identifier(alias))
+ self.writeline('l_%s = getattr(included_template, '
+ '%r, missing)' % (alias, name))
+ self.writeline('if l_%s is missing:' % alias)
self.indent()
- self.writeline('%s = environment.undefined(%r %% '
+ self.writeline('l_%s = environment.undefined(%r %% '
'included_template.name, '
'name=included_template.name)' %
- (mask_identifier(alias), 'the template %r does '
- 'not export the requested name ' + repr(name)))
+ (alias, 'the template %r does not export '
+ 'the requested name ' + repr(name)))
self.outdent()
if frame.toplevel:
- self.writeline('context.vars[%r] = %s' %
- (alias, mask_identifier(alias)))
+ self.writeline('context.vars[%r] = l_%s' % (alias, alias))
if not alias.startswith('__'):
self.writeline('context.exported_vars.discard(%r)' % alias)
# reset the aliases if there are any.
for name, alias in aliases.iteritems():
- self.writeline('%s = %s' % (mask_identifier(name), alias))
+ self.writeline('l_%s = %s' % (name, alias))
def visit_If(self, node, frame):
if_frame = frame.soft()
arg_tuple = ', '.join(repr(x.name) for x in node.args)
if len(node.args) == 1:
arg_tuple += ','
- self.write('%s = Macro(environment, macro, %r, (%s), (' %
- (mask_identifier(node.name), node.name, arg_tuple))
+ self.write('l_%s = Macro(environment, macro, %r, (%s), (' %
+ (node.name, node.name, arg_tuple))
for arg in node.defaults:
self.visit(arg, macro_frame)
self.write(', ')
# make sure toplevel assignments are added to the context.
if frame.toplevel:
for name in assignment_frame.assigned_names:
- self.writeline('context.vars[%r] = %s' %
- (name, mask_identifier(name)))
+ self.writeline('context.vars[%r] = l_%s' % (name, name))
if not name.startswith('__'):
self.writeline('context.exported_vars.add(%r)' % name)
def visit_Name(self, node, frame):
if node.ctx == 'store' and frame.toplevel:
frame.assigned_names.add(node.name)
- self.write(mask_identifier(node.name))
+ self.write('l_' + node.name)
def visit_MarkSafe(self, node, frame):
self.write('Markup(')
string_re = re.compile(r"('([^'\\]*(?:\\.[^'\\]*)*)'"
r'|"([^"\\]*(?:\\.[^"\\]*)*)")(?ms)')
integer_re = re.compile(r'\d+')
-name_re = re.compile(r'\b[^\W\d]\w*\b(?u)')
+name_re = re.compile(r'\b[a-zA-Z_][a-zA-Z0-9_]*\b')
float_re = re.compile(r'\d+\.\d+')
# bind operators to token types
}
-def _trystr(s):
- try:
- return str(s)
- except UnicodeError:
- return s
-
-
def unescape_string(lineno, filename, s):
r"""Unescape a string. Supported escapes:
\a, \n, \r\, \f, \v, \\, \", \', \0
\x00, \u0000, \U00000000, \N{...}
"""
try:
- return _trystr(s.encode('ascii', 'backslashreplace')
- .decode('unicode-escape'))
+ return s.encode('ascii', 'backslashreplace').decode('unicode-escape')
except UnicodeError, e:
msg = str(e).split(':')[-1].strip()
raise TemplateSyntaxError(msg, lineno, filename)
elif token in ('raw_begin', 'raw_end'):
continue
elif token == 'data':
- value = _trystr(value)
+ try:
+ value = str(value)
+ except UnicodeError:
+ pass
elif token == 'keyword':
token = value
elif token == 'name':
- value = _trystr(value)
+ value = str(value)
elif token == 'string':
value = unescape_string(lineno, filename, value[1:-1])
+ try:
+ value = str(value)
+ except UnicodeError:
+ pass
elif token == 'integer':
value = int(value)
elif token == 'float':