from jinja2 import nodes
from jinja2.visitor import NodeVisitor, NodeTransformer
from jinja2.exceptions import TemplateAssertionError
-from jinja2.utils import Markup, concat
+from jinja2.utils import Markup, concat, escape
operators = {
body = []
for child in node.nodes:
try:
- const = unicode(child.as_const())
+ const = child.as_const()
+ except nodes.Impossible:
+ body.append(child)
+ continue
+ try:
+ if self.environment.autoescape:
+ if hasattr(const, '__html__'):
+ const = const.__html__()
+ else:
+ const = escape(const)
+ const = unicode(const)
except:
+ # if something goes wrong here we evaluate the node
+ # at runtime for easier debugging
body.append(child)
continue
if body and isinstance(body[-1], list):
def __init__(self, gen):
self._gen = gen
- self._next = gen.next
- self.buffered = False
+ self.disable_buffering()
def disable_buffering(self):
"""Disable the output buffering."""
class _GroupTuple(tuple):
__slots__ = ()
- grouper = property(itemgetter(0))
- list = property(itemgetter(1))
+ grouper, list = (property(itemgetter(x)) for x in xrange(2))
def __new__(cls, (key, value)):
return tuple.__new__(cls, (key, list(value)))
return self.next()
def skip_if(self, expr):
- """Like `next_if` but only returns `True` or `False`."""
+ """Like :meth:`next_if` but only returns `True` or `False`."""
return self.next_if(expr) is not None
def next(self):
"""
fields = ('nodes',)
- def optimized_nodes(self):
- """Try to optimize the nodes."""
- buffer = []
- for node in self.nodes:
- try:
- const = unicode(node.as_const())
- except:
- buffer.append(node)
- else:
- if buffer and isinstance(buffer[-1], unicode):
- buffer[-1] += const
- else:
- buffer.append(const)
- return buffer
-
class Extends(Stmt):
"""Represents an extends statement."""
env = Environment(extensions=[TestExtension])
tmpl = env.from_string('{% test %}')
assert tmpl.render() == 'False|42|23|{}'
+
+
+def test_identifier():
+ assert TestExtension.identifier == __name__ + '.TestExtension'
def test_forceescape(env):
tmpl = env.from_string('{{ x|forceescape }}')
assert tmpl.render(x=Markup('<div />')) == u'<div />'
+
+
+def test_safe():
+ env = Environment(autoescape=True)
+ tmpl = env.from_string('{{ "<div>foo</div>"|safe }}')
+ assert tmpl.render() == '<div>foo</div>'
+ tmpl = env.from_string('{{ "<div>foo</div>" }}')
+ assert tmpl.render() == '<div>foo</div>'
assert Markup(Foo()) == '<em>awesome</em>'
assert Markup('<strong>%s</strong>') % Foo() == \
'<strong><em>awesome</em></strong>'
+
+ # escaping and unescaping
+ assert escape('"<>&\'') == '"<>&''
+ assert Markup("<em>Foo & Bar</em>").striptags() == "Foo & Bar"
+ assert Markup("<test>").unescape() == "<test>"