template.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2009 Facebook
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  6. # not use this file except in compliance with the License. You may obtain
  7. # a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. # License for the specific language governing permissions and limitations
  15. # under the License.
  16. """A simple template system that compiles templates to Python code.
  17. Basic usage looks like::
  18. t = template.Template("<html>{{ myvalue }}</html>")
  19. print t.generate(myvalue="XXX")
  20. `Loader` is a class that loads templates from a root directory and caches
  21. the compiled templates::
  22. loader = template.Loader("/home/btaylor")
  23. print loader.load("test.html").generate(myvalue="XXX")
  24. We compile all templates to raw Python. Error-reporting is currently... uh,
  25. interesting. Syntax for the templates::
  26. ### base.html
  27. <html>
  28. <head>
  29. <title>{% block title %}Default title{% end %}</title>
  30. </head>
  31. <body>
  32. <ul>
  33. {% for student in students %}
  34. {% block student %}
  35. <li>{{ escape(student.name) }}</li>
  36. {% end %}
  37. {% end %}
  38. </ul>
  39. </body>
  40. </html>
  41. ### bold.html
  42. {% extends "base.html" %}
  43. {% block title %}A bolder title{% end %}
  44. {% block student %}
  45. <li><span style="bold">{{ escape(student.name) }}</span></li>
  46. {% end %}
  47. Unlike most other template systems, we do not put any restrictions on the
  48. expressions you can include in your statements. ``if`` and ``for`` blocks get
  49. translated exactly into Python, so you can do complex expressions like::
  50. {% for student in [p for p in people if p.student and p.age > 23] %}
  51. <li>{{ escape(student.name) }}</li>
  52. {% end %}
  53. Translating directly to Python means you can apply functions to expressions
  54. easily, like the ``escape()`` function in the examples above. You can pass
  55. functions in to your template just like any other variable
  56. (In a `.RequestHandler`, override `.RequestHandler.get_template_namespace`)::
  57. ### Python code
  58. def add(x, y):
  59. return x + y
  60. template.execute(add=add)
  61. ### The template
  62. {{ add(1, 2) }}
  63. We provide the functions `escape() <.xhtml_escape>`, `.url_escape()`,
  64. `.json_encode()`, and `.squeeze()` to all templates by default.
  65. Typical applications do not create `Template` or `Loader` instances by
  66. hand, but instead use the `~.RequestHandler.render` and
  67. `~.RequestHandler.render_string` methods of
  68. `tornado.web.RequestHandler`, which load templates automatically based
  69. on the ``template_path`` `.Application` setting.
  70. Variable names beginning with ``_tt_`` are reserved by the template
  71. system and should not be used by application code.
  72. Syntax Reference
  73. ----------------
  74. Template expressions are surrounded by double curly braces: ``{{ ... }}``.
  75. The contents may be any python expression, which will be escaped according
  76. to the current autoescape setting and inserted into the output. Other
  77. template directives use ``{% %}``. These tags may be escaped as ``{{!``
  78. and ``{%!`` if you need to include a literal ``{{`` or ``{%`` in the output.
  79. To comment out a section so that it is omitted from the output, surround it
  80. with ``{# ... #}``.
  81. ``{% apply *function* %}...{% end %}``
  82. Applies a function to the output of all template code between ``apply``
  83. and ``end``::
  84. {% apply linkify %}{{name}} said: {{message}}{% end %}
  85. Note that as an implementation detail apply blocks are implemented
  86. as nested functions and thus may interact strangely with variables
  87. set via ``{% set %}``, or the use of ``{% break %}`` or ``{% continue %}``
  88. within loops.
  89. ``{% autoescape *function* %}``
  90. Sets the autoescape mode for the current file. This does not affect
  91. other files, even those referenced by ``{% include %}``. Note that
  92. autoescaping can also be configured globally, at the `.Application`
  93. or `Loader`.::
  94. {% autoescape xhtml_escape %}
  95. {% autoescape None %}
  96. ``{% block *name* %}...{% end %}``
  97. Indicates a named, replaceable block for use with ``{% extends %}``.
  98. Blocks in the parent template will be replaced with the contents of
  99. the same-named block in a child template.::
  100. <!-- base.html -->
  101. <title>{% block title %}Default title{% end %}</title>
  102. <!-- mypage.html -->
  103. {% extends "base.html" %}
  104. {% block title %}My page title{% end %}
  105. ``{% comment ... %}``
  106. A comment which will be removed from the template output. Note that
  107. there is no ``{% end %}`` tag; the comment goes from the word ``comment``
  108. to the closing ``%}`` tag.
  109. ``{% extends *filename* %}``
  110. Inherit from another template. Templates that use ``extends`` should
  111. contain one or more ``block`` tags to replace content from the parent
  112. template. Anything in the child template not contained in a ``block``
  113. tag will be ignored. For an example, see the ``{% block %}`` tag.
  114. ``{% for *var* in *expr* %}...{% end %}``
  115. Same as the python ``for`` statement. ``{% break %}`` and
  116. ``{% continue %}`` may be used inside the loop.
  117. ``{% from *x* import *y* %}``
  118. Same as the python ``import`` statement.
  119. ``{% if *condition* %}...{% elif *condition* %}...{% else %}...{% end %}``
  120. Conditional statement - outputs the first section whose condition is
  121. true. (The ``elif`` and ``else`` sections are optional)
  122. ``{% import *module* %}``
  123. Same as the python ``import`` statement.
  124. ``{% include *filename* %}``
  125. Includes another template file. The included file can see all the local
  126. variables as if it were copied directly to the point of the ``include``
  127. directive (the ``{% autoescape %}`` directive is an exception).
  128. Alternately, ``{% module Template(filename, **kwargs) %}`` may be used
  129. to include another template with an isolated namespace.
  130. ``{% module *expr* %}``
  131. Renders a `~tornado.web.UIModule`. The output of the ``UIModule`` is
  132. not escaped::
  133. {% module Template("foo.html", arg=42) %}
  134. ``UIModules`` are a feature of the `tornado.web.RequestHandler`
  135. class (and specifically its ``render`` method) and will not work
  136. when the template system is used on its own in other contexts.
  137. ``{% raw *expr* %}``
  138. Outputs the result of the given expression without autoescaping.
  139. ``{% set *x* = *y* %}``
  140. Sets a local variable.
  141. ``{% try %}...{% except %}...{% else %}...{% finally %}...{% end %}``
  142. Same as the python ``try`` statement.
  143. ``{% while *condition* %}... {% end %}``
  144. Same as the python ``while`` statement. ``{% break %}`` and
  145. ``{% continue %}`` may be used inside the loop.
  146. ``{% whitespace *mode* %}``
  147. Sets the whitespace mode for the remainder of the current file
  148. (or until the next ``{% whitespace %}`` directive). See
  149. `filter_whitespace` for available options. New in Tornado 4.3.
  150. """
  151. from __future__ import absolute_import, division, print_function, with_statement
  152. import datetime
  153. import linecache
  154. import os.path
  155. import posixpath
  156. import re
  157. import threading
  158. from tornado import escape
  159. from tornado.log import app_log
  160. from tornado.util import ObjectDict, exec_in, unicode_type
  161. try:
  162. from cStringIO import StringIO # py2
  163. except ImportError:
  164. from io import StringIO # py3
  165. _DEFAULT_AUTOESCAPE = "xhtml_escape"
  166. _UNSET = object()
  167. def filter_whitespace(mode, text):
  168. """Transform whitespace in ``text`` according to ``mode``.
  169. Available modes are:
  170. * ``all``: Return all whitespace unmodified.
  171. * ``single``: Collapse consecutive whitespace with a single whitespace
  172. character, preserving newlines.
  173. * ``oneline``: Collapse all runs of whitespace into a single space
  174. character, removing all newlines in the process.
  175. .. versionadded:: 4.3
  176. """
  177. if mode == 'all':
  178. return text
  179. elif mode == 'single':
  180. text = re.sub(r"([\t ]+)", " ", text)
  181. text = re.sub(r"(\s*\n\s*)", "\n", text)
  182. return text
  183. elif mode == 'oneline':
  184. return re.sub(r"(\s+)", " ", text)
  185. else:
  186. raise Exception("invalid whitespace mode %s" % mode)
  187. class Template(object):
  188. """A compiled template.
  189. We compile into Python from the given template_string. You can generate
  190. the template from variables with generate().
  191. """
  192. # note that the constructor's signature is not extracted with
  193. # autodoc because _UNSET looks like garbage. When changing
  194. # this signature update website/sphinx/template.rst too.
  195. def __init__(self, template_string, name="<string>", loader=None,
  196. compress_whitespace=_UNSET, autoescape=_UNSET,
  197. whitespace=None):
  198. """Construct a Template.
  199. :arg str template_string: the contents of the template file.
  200. :arg str name: the filename from which the template was loaded
  201. (used for error message).
  202. :arg tornado.template.BaseLoader loader: the `~tornado.template.BaseLoader` responsible for this template,
  203. used to resolve ``{% include %}`` and ``{% extend %}``
  204. directives.
  205. :arg bool compress_whitespace: Deprecated since Tornado 4.3.
  206. Equivalent to ``whitespace="single"`` if true and
  207. ``whitespace="all"`` if false.
  208. :arg str autoescape: The name of a function in the template
  209. namespace, or ``None`` to disable escaping by default.
  210. :arg str whitespace: A string specifying treatment of whitespace;
  211. see `filter_whitespace` for options.
  212. .. versionchanged:: 4.3
  213. Added ``whitespace`` parameter; deprecated ``compress_whitespace``.
  214. """
  215. self.name = escape.native_str(name)
  216. if compress_whitespace is not _UNSET:
  217. # Convert deprecated compress_whitespace (bool) to whitespace (str).
  218. if whitespace is not None:
  219. raise Exception("cannot set both whitespace and compress_whitespace")
  220. whitespace = "single" if compress_whitespace else "all"
  221. if whitespace is None:
  222. if loader and loader.whitespace:
  223. whitespace = loader.whitespace
  224. else:
  225. # Whitespace defaults by filename.
  226. if name.endswith(".html") or name.endswith(".js"):
  227. whitespace = "single"
  228. else:
  229. whitespace = "all"
  230. # Validate the whitespace setting.
  231. filter_whitespace(whitespace, '')
  232. if autoescape is not _UNSET:
  233. self.autoescape = autoescape
  234. elif loader:
  235. self.autoescape = loader.autoescape
  236. else:
  237. self.autoescape = _DEFAULT_AUTOESCAPE
  238. self.namespace = loader.namespace if loader else {}
  239. reader = _TemplateReader(name, escape.native_str(template_string),
  240. whitespace)
  241. self.file = _File(self, _parse(reader, self))
  242. self.code = self._generate_python(loader)
  243. self.loader = loader
  244. try:
  245. # Under python2.5, the fake filename used here must match
  246. # the module name used in __name__ below.
  247. # The dont_inherit flag prevents template.py's future imports
  248. # from being applied to the generated code.
  249. self.compiled = compile(
  250. escape.to_unicode(self.code),
  251. "%s.generated.py" % self.name.replace('.', '_'),
  252. "exec", dont_inherit=True)
  253. except Exception:
  254. formatted_code = _format_code(self.code).rstrip()
  255. app_log.error("%s code:\n%s", self.name, formatted_code)
  256. raise
  257. def generate(self, **kwargs):
  258. """Generate this template with the given arguments."""
  259. namespace = {
  260. "escape": escape.xhtml_escape,
  261. "xhtml_escape": escape.xhtml_escape,
  262. "url_escape": escape.url_escape,
  263. "json_encode": escape.json_encode,
  264. "squeeze": escape.squeeze,
  265. "linkify": escape.linkify,
  266. "datetime": datetime,
  267. "_tt_utf8": escape.utf8, # for internal use
  268. "_tt_string_types": (unicode_type, bytes),
  269. # __name__ and __loader__ allow the traceback mechanism to find
  270. # the generated source code.
  271. "__name__": self.name.replace('.', '_'),
  272. "__loader__": ObjectDict(get_source=lambda name: self.code),
  273. }
  274. namespace.update(self.namespace)
  275. namespace.update(kwargs)
  276. exec_in(self.compiled, namespace)
  277. execute = namespace["_tt_execute"]
  278. # Clear the traceback module's cache of source data now that
  279. # we've generated a new template (mainly for this module's
  280. # unittests, where different tests reuse the same name).
  281. linecache.clearcache()
  282. return execute()
  283. def _generate_python(self, loader):
  284. buffer = StringIO()
  285. try:
  286. # named_blocks maps from names to _NamedBlock objects
  287. named_blocks = {}
  288. ancestors = self._get_ancestors(loader)
  289. ancestors.reverse()
  290. for ancestor in ancestors:
  291. ancestor.find_named_blocks(loader, named_blocks)
  292. writer = _CodeWriter(buffer, named_blocks, loader,
  293. ancestors[0].template)
  294. ancestors[0].generate(writer)
  295. return buffer.getvalue()
  296. finally:
  297. buffer.close()
  298. def _get_ancestors(self, loader):
  299. ancestors = [self.file]
  300. for chunk in self.file.body.chunks:
  301. if isinstance(chunk, _ExtendsBlock):
  302. if not loader:
  303. raise ParseError("{% extends %} block found, but no "
  304. "template loader")
  305. template = loader.load(chunk.name, self.name)
  306. ancestors.extend(template._get_ancestors(loader))
  307. return ancestors
  308. class BaseLoader(object):
  309. """Base class for template loaders.
  310. You must use a template loader to use template constructs like
  311. ``{% extends %}`` and ``{% include %}``. The loader caches all
  312. templates after they are loaded the first time.
  313. """
  314. def __init__(self, autoescape=_DEFAULT_AUTOESCAPE, namespace=None,
  315. whitespace=None):
  316. """Construct a template loader.
  317. :arg str autoescape: The name of a function in the template
  318. namespace, such as "xhtml_escape", or ``None`` to disable
  319. autoescaping by default.
  320. :arg dict namespace: A dictionary to be added to the default template
  321. namespace, or ``None``.
  322. :arg str whitespace: A string specifying default behavior for
  323. whitespace in templates; see `filter_whitespace` for options.
  324. Default is "single" for files ending in ".html" and ".js" and
  325. "all" for other files.
  326. .. versionchanged:: 4.3
  327. Added ``whitespace`` parameter.
  328. """
  329. self.autoescape = autoescape
  330. self.namespace = namespace or {}
  331. self.whitespace = whitespace
  332. self.templates = {}
  333. # self.lock protects self.templates. It's a reentrant lock
  334. # because templates may load other templates via `include` or
  335. # `extends`. Note that thanks to the GIL this code would be safe
  336. # even without the lock, but could lead to wasted work as multiple
  337. # threads tried to compile the same template simultaneously.
  338. self.lock = threading.RLock()
  339. def reset(self):
  340. """Resets the cache of compiled templates."""
  341. with self.lock:
  342. self.templates = {}
  343. def resolve_path(self, name, parent_path=None):
  344. """Converts a possibly-relative path to absolute (used internally)."""
  345. raise NotImplementedError()
  346. def load(self, name, parent_path=None):
  347. """Loads a template."""
  348. name = self.resolve_path(name, parent_path=parent_path)
  349. with self.lock:
  350. if name not in self.templates:
  351. self.templates[name] = self._create_template(name)
  352. return self.templates[name]
  353. def _create_template(self, name):
  354. raise NotImplementedError()
  355. class Loader(BaseLoader):
  356. """A template loader that loads from a single root directory.
  357. """
  358. def __init__(self, root_directory, **kwargs):
  359. super(Loader, self).__init__(**kwargs)
  360. self.root = os.path.abspath(root_directory)
  361. def resolve_path(self, name, parent_path=None):
  362. if parent_path and not parent_path.startswith("<") and \
  363. not parent_path.startswith("/") and \
  364. not name.startswith("/"):
  365. current_path = os.path.join(self.root, parent_path)
  366. file_dir = os.path.dirname(os.path.abspath(current_path))
  367. relative_path = os.path.abspath(os.path.join(file_dir, name))
  368. if relative_path.startswith(self.root):
  369. name = relative_path[len(self.root) + 1:]
  370. return name
  371. def _create_template(self, name):
  372. path = os.path.join(self.root, name)
  373. with open(path, "rb") as f:
  374. template = Template(f.read(), name=name, loader=self)
  375. return template
  376. class DictLoader(BaseLoader):
  377. """A template loader that loads from a dictionary."""
  378. def __init__(self, dict, **kwargs):
  379. super(DictLoader, self).__init__(**kwargs)
  380. self.dict = dict
  381. def resolve_path(self, name, parent_path=None):
  382. if parent_path and not parent_path.startswith("<") and \
  383. not parent_path.startswith("/") and \
  384. not name.startswith("/"):
  385. file_dir = posixpath.dirname(parent_path)
  386. name = posixpath.normpath(posixpath.join(file_dir, name))
  387. return name
  388. def _create_template(self, name):
  389. return Template(self.dict[name], name=name, loader=self)
  390. class _Node(object):
  391. def each_child(self):
  392. return ()
  393. def generate(self, writer):
  394. raise NotImplementedError()
  395. def find_named_blocks(self, loader, named_blocks):
  396. for child in self.each_child():
  397. child.find_named_blocks(loader, named_blocks)
  398. class _File(_Node):
  399. def __init__(self, template, body):
  400. self.template = template
  401. self.body = body
  402. self.line = 0
  403. def generate(self, writer):
  404. writer.write_line("def _tt_execute():", self.line)
  405. with writer.indent():
  406. writer.write_line("_tt_buffer = []", self.line)
  407. writer.write_line("_tt_append = _tt_buffer.append", self.line)
  408. self.body.generate(writer)
  409. writer.write_line("return _tt_utf8('').join(_tt_buffer)", self.line)
  410. def each_child(self):
  411. return (self.body,)
  412. class _ChunkList(_Node):
  413. def __init__(self, chunks):
  414. self.chunks = chunks
  415. def generate(self, writer):
  416. for chunk in self.chunks:
  417. chunk.generate(writer)
  418. def each_child(self):
  419. return self.chunks
  420. class _NamedBlock(_Node):
  421. def __init__(self, name, body, template, line):
  422. self.name = name
  423. self.body = body
  424. self.template = template
  425. self.line = line
  426. def each_child(self):
  427. return (self.body,)
  428. def generate(self, writer):
  429. block = writer.named_blocks[self.name]
  430. with writer.include(block.template, self.line):
  431. block.body.generate(writer)
  432. def find_named_blocks(self, loader, named_blocks):
  433. named_blocks[self.name] = self
  434. _Node.find_named_blocks(self, loader, named_blocks)
  435. class _ExtendsBlock(_Node):
  436. def __init__(self, name):
  437. self.name = name
  438. class _IncludeBlock(_Node):
  439. def __init__(self, name, reader, line):
  440. self.name = name
  441. self.template_name = reader.name
  442. self.line = line
  443. def find_named_blocks(self, loader, named_blocks):
  444. included = loader.load(self.name, self.template_name)
  445. included.file.find_named_blocks(loader, named_blocks)
  446. def generate(self, writer):
  447. included = writer.loader.load(self.name, self.template_name)
  448. with writer.include(included, self.line):
  449. included.file.body.generate(writer)
  450. class _ApplyBlock(_Node):
  451. def __init__(self, method, line, body=None):
  452. self.method = method
  453. self.line = line
  454. self.body = body
  455. def each_child(self):
  456. return (self.body,)
  457. def generate(self, writer):
  458. method_name = "_tt_apply%d" % writer.apply_counter
  459. writer.apply_counter += 1
  460. writer.write_line("def %s():" % method_name, self.line)
  461. with writer.indent():
  462. writer.write_line("_tt_buffer = []", self.line)
  463. writer.write_line("_tt_append = _tt_buffer.append", self.line)
  464. self.body.generate(writer)
  465. writer.write_line("return _tt_utf8('').join(_tt_buffer)", self.line)
  466. writer.write_line("_tt_append(_tt_utf8(%s(%s())))" % (
  467. self.method, method_name), self.line)
  468. class _ControlBlock(_Node):
  469. def __init__(self, statement, line, body=None):
  470. self.statement = statement
  471. self.line = line
  472. self.body = body
  473. def each_child(self):
  474. return (self.body,)
  475. def generate(self, writer):
  476. writer.write_line("%s:" % self.statement, self.line)
  477. with writer.indent():
  478. self.body.generate(writer)
  479. # Just in case the body was empty
  480. writer.write_line("pass", self.line)
  481. class _IntermediateControlBlock(_Node):
  482. def __init__(self, statement, line):
  483. self.statement = statement
  484. self.line = line
  485. def generate(self, writer):
  486. # In case the previous block was empty
  487. writer.write_line("pass", self.line)
  488. writer.write_line("%s:" % self.statement, self.line, writer.indent_size() - 1)
  489. class _Statement(_Node):
  490. def __init__(self, statement, line):
  491. self.statement = statement
  492. self.line = line
  493. def generate(self, writer):
  494. writer.write_line(self.statement, self.line)
  495. class _Expression(_Node):
  496. def __init__(self, expression, line, raw=False):
  497. self.expression = expression
  498. self.line = line
  499. self.raw = raw
  500. def generate(self, writer):
  501. writer.write_line("_tt_tmp = %s" % self.expression, self.line)
  502. writer.write_line("if isinstance(_tt_tmp, _tt_string_types):"
  503. " _tt_tmp = _tt_utf8(_tt_tmp)", self.line)
  504. writer.write_line("else: _tt_tmp = _tt_utf8(str(_tt_tmp))", self.line)
  505. if not self.raw and writer.current_template.autoescape is not None:
  506. # In python3 functions like xhtml_escape return unicode,
  507. # so we have to convert to utf8 again.
  508. writer.write_line("_tt_tmp = _tt_utf8(%s(_tt_tmp))" %
  509. writer.current_template.autoescape, self.line)
  510. writer.write_line("_tt_append(_tt_tmp)", self.line)
  511. class _Module(_Expression):
  512. def __init__(self, expression, line):
  513. super(_Module, self).__init__("_tt_modules." + expression, line,
  514. raw=True)
  515. class _Text(_Node):
  516. def __init__(self, value, line, whitespace):
  517. self.value = value
  518. self.line = line
  519. self.whitespace = whitespace
  520. def generate(self, writer):
  521. value = self.value
  522. # Compress whitespace if requested, with a crude heuristic to avoid
  523. # altering preformatted whitespace.
  524. if "<pre>" not in value:
  525. value = filter_whitespace(self.whitespace, value)
  526. if value:
  527. writer.write_line('_tt_append(%r)' % escape.utf8(value), self.line)
  528. class ParseError(Exception):
  529. """Raised for template syntax errors.
  530. ``ParseError`` instances have ``filename`` and ``lineno`` attributes
  531. indicating the position of the error.
  532. .. versionchanged:: 4.3
  533. Added ``filename`` and ``lineno`` attributes.
  534. """
  535. def __init__(self, message, filename, lineno):
  536. self.message = message
  537. # The names "filename" and "lineno" are chosen for consistency
  538. # with python SyntaxError.
  539. self.filename = filename
  540. self.lineno = lineno
  541. def __str__(self):
  542. return '%s at %s:%d' % (self.message, self.filename, self.lineno)
  543. class _CodeWriter(object):
  544. def __init__(self, file, named_blocks, loader, current_template):
  545. self.file = file
  546. self.named_blocks = named_blocks
  547. self.loader = loader
  548. self.current_template = current_template
  549. self.apply_counter = 0
  550. self.include_stack = []
  551. self._indent = 0
  552. def indent_size(self):
  553. return self._indent
  554. def indent(self):
  555. class Indenter(object):
  556. def __enter__(_):
  557. self._indent += 1
  558. return self
  559. def __exit__(_, *args):
  560. assert self._indent > 0
  561. self._indent -= 1
  562. return Indenter()
  563. def include(self, template, line):
  564. self.include_stack.append((self.current_template, line))
  565. self.current_template = template
  566. class IncludeTemplate(object):
  567. def __enter__(_):
  568. return self
  569. def __exit__(_, *args):
  570. self.current_template = self.include_stack.pop()[0]
  571. return IncludeTemplate()
  572. def write_line(self, line, line_number, indent=None):
  573. if indent is None:
  574. indent = self._indent
  575. line_comment = ' # %s:%d' % (self.current_template.name, line_number)
  576. if self.include_stack:
  577. ancestors = ["%s:%d" % (tmpl.name, lineno)
  578. for (tmpl, lineno) in self.include_stack]
  579. line_comment += ' (via %s)' % ', '.join(reversed(ancestors))
  580. print(" " * indent + line + line_comment, file=self.file)
  581. class _TemplateReader(object):
  582. def __init__(self, name, text, whitespace):
  583. self.name = name
  584. self.text = text
  585. self.whitespace = whitespace
  586. self.line = 1
  587. self.pos = 0
  588. def find(self, needle, start=0, end=None):
  589. assert start >= 0, start
  590. pos = self.pos
  591. start += pos
  592. if end is None:
  593. index = self.text.find(needle, start)
  594. else:
  595. end += pos
  596. assert end >= start
  597. index = self.text.find(needle, start, end)
  598. if index != -1:
  599. index -= pos
  600. return index
  601. def consume(self, count=None):
  602. if count is None:
  603. count = len(self.text) - self.pos
  604. newpos = self.pos + count
  605. self.line += self.text.count("\n", self.pos, newpos)
  606. s = self.text[self.pos:newpos]
  607. self.pos = newpos
  608. return s
  609. def remaining(self):
  610. return len(self.text) - self.pos
  611. def __len__(self):
  612. return self.remaining()
  613. def __getitem__(self, key):
  614. if type(key) is slice:
  615. size = len(self)
  616. start, stop, step = key.indices(size)
  617. if start is None:
  618. start = self.pos
  619. else:
  620. start += self.pos
  621. if stop is not None:
  622. stop += self.pos
  623. return self.text[slice(start, stop, step)]
  624. elif key < 0:
  625. return self.text[key]
  626. else:
  627. return self.text[self.pos + key]
  628. def __str__(self):
  629. return self.text[self.pos:]
  630. def raise_parse_error(self, msg):
  631. raise ParseError(msg, self.name, self.line)
  632. def _format_code(code):
  633. lines = code.splitlines()
  634. format = "%%%dd %%s\n" % len(repr(len(lines) + 1))
  635. return "".join([format % (i + 1, line) for (i, line) in enumerate(lines)])
  636. def _parse(reader, template, in_block=None, in_loop=None):
  637. body = _ChunkList([])
  638. while True:
  639. # Find next template directive
  640. curly = 0
  641. while True:
  642. curly = reader.find("{", curly)
  643. if curly == -1 or curly + 1 == reader.remaining():
  644. # EOF
  645. if in_block:
  646. reader.raise_parse_error(
  647. "Missing {%% end %%} block for %s" % in_block)
  648. body.chunks.append(_Text(reader.consume(), reader.line,
  649. reader.whitespace))
  650. return body
  651. # If the first curly brace is not the start of a special token,
  652. # start searching from the character after it
  653. if reader[curly + 1] not in ("{", "%", "#"):
  654. curly += 1
  655. continue
  656. # When there are more than 2 curlies in a row, use the
  657. # innermost ones. This is useful when generating languages
  658. # like latex where curlies are also meaningful
  659. if (curly + 2 < reader.remaining() and
  660. reader[curly + 1] == '{' and reader[curly + 2] == '{'):
  661. curly += 1
  662. continue
  663. break
  664. # Append any text before the special token
  665. if curly > 0:
  666. cons = reader.consume(curly)
  667. body.chunks.append(_Text(cons, reader.line,
  668. reader.whitespace))
  669. start_brace = reader.consume(2)
  670. line = reader.line
  671. # Template directives may be escaped as "{{!" or "{%!".
  672. # In this case output the braces and consume the "!".
  673. # This is especially useful in conjunction with jquery templates,
  674. # which also use double braces.
  675. if reader.remaining() and reader[0] == "!":
  676. reader.consume(1)
  677. body.chunks.append(_Text(start_brace, line,
  678. reader.whitespace))
  679. continue
  680. # Comment
  681. if start_brace == "{#":
  682. end = reader.find("#}")
  683. if end == -1:
  684. reader.raise_parse_error("Missing end comment #}")
  685. contents = reader.consume(end).strip()
  686. reader.consume(2)
  687. continue
  688. # Expression
  689. if start_brace == "{{":
  690. end = reader.find("}}")
  691. if end == -1:
  692. reader.raise_parse_error("Missing end expression }}")
  693. contents = reader.consume(end).strip()
  694. reader.consume(2)
  695. if not contents:
  696. reader.raise_parse_error("Empty expression")
  697. body.chunks.append(_Expression(contents, line))
  698. continue
  699. # Block
  700. assert start_brace == "{%", start_brace
  701. end = reader.find("%}")
  702. if end == -1:
  703. reader.raise_parse_error("Missing end block %}")
  704. contents = reader.consume(end).strip()
  705. reader.consume(2)
  706. if not contents:
  707. reader.raise_parse_error("Empty block tag ({% %})")
  708. operator, space, suffix = contents.partition(" ")
  709. suffix = suffix.strip()
  710. # Intermediate ("else", "elif", etc) blocks
  711. intermediate_blocks = {
  712. "else": set(["if", "for", "while", "try"]),
  713. "elif": set(["if"]),
  714. "except": set(["try"]),
  715. "finally": set(["try"]),
  716. }
  717. allowed_parents = intermediate_blocks.get(operator)
  718. if allowed_parents is not None:
  719. if not in_block:
  720. reader.raise_parse_error("%s outside %s block" %
  721. (operator, allowed_parents))
  722. if in_block not in allowed_parents:
  723. reader.raise_parse_error(
  724. "%s block cannot be attached to %s block" %
  725. (operator, in_block))
  726. body.chunks.append(_IntermediateControlBlock(contents, line))
  727. continue
  728. # End tag
  729. elif operator == "end":
  730. if not in_block:
  731. reader.raise_parse_error("Extra {% end %} block")
  732. return body
  733. elif operator in ("extends", "include", "set", "import", "from",
  734. "comment", "autoescape", "whitespace", "raw",
  735. "module"):
  736. if operator == "comment":
  737. continue
  738. if operator == "extends":
  739. suffix = suffix.strip('"').strip("'")
  740. if not suffix:
  741. reader.raise_parse_error("extends missing file path")
  742. block = _ExtendsBlock(suffix)
  743. elif operator in ("import", "from"):
  744. if not suffix:
  745. reader.raise_parse_error("import missing statement")
  746. block = _Statement(contents, line)
  747. elif operator == "include":
  748. suffix = suffix.strip('"').strip("'")
  749. if not suffix:
  750. reader.raise_parse_error("include missing file path")
  751. block = _IncludeBlock(suffix, reader, line)
  752. elif operator == "set":
  753. if not suffix:
  754. reader.raise_parse_error("set missing statement")
  755. block = _Statement(suffix, line)
  756. elif operator == "autoescape":
  757. fn = suffix.strip()
  758. if fn == "None":
  759. fn = None
  760. template.autoescape = fn
  761. continue
  762. elif operator == "whitespace":
  763. mode = suffix.strip()
  764. # Validate the selected mode
  765. filter_whitespace(mode, '')
  766. reader.whitespace = mode
  767. continue
  768. elif operator == "raw":
  769. block = _Expression(suffix, line, raw=True)
  770. elif operator == "module":
  771. block = _Module(suffix, line)
  772. body.chunks.append(block)
  773. continue
  774. elif operator in ("apply", "block", "try", "if", "for", "while"):
  775. # parse inner body recursively
  776. if operator in ("for", "while"):
  777. block_body = _parse(reader, template, operator, operator)
  778. elif operator == "apply":
  779. # apply creates a nested function so syntactically it's not
  780. # in the loop.
  781. block_body = _parse(reader, template, operator, None)
  782. else:
  783. block_body = _parse(reader, template, operator, in_loop)
  784. if operator == "apply":
  785. if not suffix:
  786. reader.raise_parse_error("apply missing method name")
  787. block = _ApplyBlock(suffix, line, block_body)
  788. elif operator == "block":
  789. if not suffix:
  790. reader.raise_parse_error("block missing name")
  791. block = _NamedBlock(suffix, block_body, template, line)
  792. else:
  793. block = _ControlBlock(contents, line, block_body)
  794. body.chunks.append(block)
  795. continue
  796. elif operator in ("break", "continue"):
  797. if not in_loop:
  798. reader.raise_parse_error("%s outside %s block" %
  799. (operator, set(["for", "while"])))
  800. body.chunks.append(_Statement(contents, line))
  801. continue
  802. else:
  803. reader.raise_parse_error("unknown operator: %r" % operator)