2 A light and fast template engine.
4 Copyright (c) 2012, Daniele Mazzocchio
7 Redistribution and use in source and binary forms, with or without modification,
8 are permitted provided that the following conditions are met:
10 * Redistributions of source code must retain the above copyright notice, this
11 list of conditions and the following disclaimer.
12 * Redistributions in binary form must reproduce the above copyright notice,
13 this list of conditions and the following disclaimer in the documentation
14 and/or other materials provided with the distribution.
15 * Neither the name of the developer nor the names of its contributors may be
16 used to endorse or promote products derived from this software without
17 specific prior written permission.
19 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
20 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
23 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
26 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 ------------------------------------------------------------------------------
32 Supplemented with escape and postprocess and buffer size options,
33 code object caching, get(), fixes and other tweaks, by Erki Suurjaak.
39 try: text_type, string_types = unicode, (bytes, unicode)
40 except Exception: text_type, string_types = str, (str, )
45 TRANSPILED_TEMPLATES = {}
46 COMPILED_TEMPLATES = {}
48 RE_STRIP = re.compile(
"(^[ \t]+|[ \t]+$|(?<=[ \t])[ \t]+|\\A[\r\n]+|[ \t\r\n]+\\Z)", re.M)
49 RE_STRIP_STREAM = re.compile(
"(^[ \t]+|[ \t]+$|(?<=[ \t])[ \t]+|\\A[\r\n]+|"
50 "((?<=(\r\n))|(?<=[ \t\r\n]))[ \t\r\n]+\\Z)", re.M)
52 def __init__(self, template, strip=True, escape=False, postprocess=None):
53 """Initialize class"""
55 pp = list([postprocess]
if callable(postprocess)
else postprocess
or [])
57 self.
options = {
"strip": strip,
"escape": escape,
"postprocess": pp}
59 key = (template, bool(escape))
60 TPLS, CODES = Template.TRANSPILED_TEMPLATES, Template.COMPILED_TEMPLATES
62 self.
code = CODES.setdefault(src, CODES.get(src)
or compile(src,
"<string>",
"exec"))
64 def expand(self, namespace=None, **kw):
65 """Return the expanded template string"""
68 return self.
_postprocess(
"".join(map(to_unicode, output)))
70 def stream(self, buffer, namespace=None, encoding="utf-8", buffer_size=65536, **kw):
71 """Expand the template and stream it to a file-like buffer."""
73 def write_buffer(s, flush=False, cache=[""]):
76 if cache[0]
and (flush
or buffer_size < 1
or len(cache[0]) > buffer_size):
78 v
and buffer.write(v.encode(encoding)
if encoding
else v)
82 write_buffer(
"", flush=
True)
85 """Return template namespace dictionary, containing given values and template functions."""
86 namespace = dict(namespace
or {}, **dict(kw, **self.
builtins))
87 namespace.update(echo=echo, get=namespace.get, isdef=namespace.__contains__)
91 """Modify template string before code conversion"""
93 o = re.compile(
"(?m)^[ \t]*%((if|for|while|try).+:)")
94 c = re.compile(
"(?m)^[ \t]*%(((else|elif|except|finally).*:)|(end\\w+))")
95 template = c.sub(
r"<%:\g<1>%>", o.sub(
r"<%\g<1>%>", template))
99 vars =
r"\{\{\s*\!(.*?)\}\}",
r"\{\{(.*?)\}\}"
100 subs = [
r"<%echo(\g<1>)%>\n"] * 2
101 if self.
options[
"escape"]: subs[1] =
r"<%echo(escape(\g<1>))%>\n"
102 for v, s
in zip(vars, subs): template = re.sub(v, s, template)
107 """Return the code generated from the template string"""
108 code_blk = re.compile(
r"<%(.*?)%>\n?", re.DOTALL)
111 for n, blk
in enumerate(code_blk.split(template)):
113 blk = re.sub(
r"<\\%",
"<%", re.sub(
r"%\\>",
"%>", blk))
115 blk = re.sub(
r"\\(%|{|})",
r"\g<1>", blk)
120 blk = re.sub(
r'\\',
r'\\\\', blk)
122 blk = re.sub(
r'"',
r'\\"', blk)
123 blk = (
" " * (indent*4)) +
'echo("""{0}""")'.format(blk)
126 if blk.lstrip().startswith(
":"):
128 err =
"unexpected block ending"
129 raise SyntaxError(
"Line {0}: {1}".format(n, err))
131 if blk.startswith(
":end"):
133 blk = blk.lstrip()[1:]
135 blk = re.sub(
"(?m)^",
" " * (indent * 4), blk)
136 if blk.endswith(
":"):
142 err =
"Reached EOF before closing block"
143 raise EOFError(
"Line {0}: {1}".format(n, err))
145 return "\n".join(code)
148 """Modify output string after variables and code evaluation"""
150 output = (Template.RE_STRIP_STREAM
if stream
else Template.RE_STRIP).sub(
"", output)
151 for process
in self.
options[
"postprocess"]:
152 output = process(output)
157 """Escape HTML special characters &<> and quotes "'."""
158 CHARS, ENTITIES =
"&<>\"'", [
"&",
"<",
">",
""",
"'"]
159 string = x
if isinstance(x, string_types)
else str(x)
160 for c, e
in zip(CHARS, ENTITIES): string = string.replace(c, e)
165 """Convert anything to Unicode."""
166 if isinstance(x, (bytes, bytearray)):
167 x =
text_type(x, encoding, errors=
"replace")
168 elif not isinstance(x, string_types):