base.py 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  1. """
  2. This is the Django template system.
  3. How it works:
  4. The Lexer.tokenize() method converts a template string (i.e., a string
  5. containing markup with custom template tags) to tokens, which can be either
  6. plain text (TokenType.TEXT), variables (TokenType.VAR), or block statements
  7. (TokenType.BLOCK).
  8. The Parser() class takes a list of tokens in its constructor, and its parse()
  9. method returns a compiled template -- which is, under the hood, a list of
  10. Node objects.
  11. Each Node is responsible for creating some sort of output -- e.g. simple text
  12. (TextNode), variable values in a given context (VariableNode), results of basic
  13. logic (IfNode), results of looping (ForNode), or anything else. The core Node
  14. types are TextNode, VariableNode, IfNode and ForNode, but plugin modules can
  15. define their own custom node types.
  16. Each Node has a render() method, which takes a Context and returns a string of
  17. the rendered node. For example, the render() method of a Variable Node returns
  18. the variable's value as a string. The render() method of a ForNode returns the
  19. rendered output of whatever was inside the loop, recursively.
  20. The Template class is a convenient wrapper that takes care of template
  21. compilation and rendering.
  22. Usage:
  23. The only thing you should ever use directly in this file is the Template class.
  24. Create a compiled template object with a template_string, then call render()
  25. with a context. In the compilation stage, the TemplateSyntaxError exception
  26. will be raised if the template doesn't have proper syntax.
  27. Sample code:
  28. >>> from django import template
  29. >>> s = '<html>{% if test %}<h1>{{ varvalue }}</h1>{% endif %}</html>'
  30. >>> t = template.Template(s)
  31. (t is now a compiled template, and its render() method can be called multiple
  32. times with multiple contexts)
  33. >>> c = template.Context({'test':True, 'varvalue': 'Hello'})
  34. >>> t.render(c)
  35. '<html><h1>Hello</h1></html>'
  36. >>> c = template.Context({'test':False, 'varvalue': 'Hello'})
  37. >>> t.render(c)
  38. '<html></html>'
  39. """
  40. import inspect
  41. import logging
  42. import re
  43. from enum import Enum
  44. from django.template.context import BaseContext
  45. from django.utils.formats import localize
  46. from django.utils.html import conditional_escape, escape
  47. from django.utils.regex_helper import _lazy_re_compile
  48. from django.utils.safestring import SafeData, SafeString, mark_safe
  49. from django.utils.text import get_text_list, smart_split, unescape_string_literal
  50. from django.utils.timezone import template_localtime
  51. from django.utils.translation import gettext_lazy, pgettext_lazy
  52. from .exceptions import TemplateSyntaxError
  53. # template syntax constants
  54. FILTER_SEPARATOR = "|"
  55. FILTER_ARGUMENT_SEPARATOR = ":"
  56. VARIABLE_ATTRIBUTE_SEPARATOR = "."
  57. BLOCK_TAG_START = "{%"
  58. BLOCK_TAG_END = "%}"
  59. VARIABLE_TAG_START = "{{"
  60. VARIABLE_TAG_END = "}}"
  61. COMMENT_TAG_START = "{#"
  62. COMMENT_TAG_END = "#}"
  63. SINGLE_BRACE_START = "{"
  64. SINGLE_BRACE_END = "}"
  65. # what to report as the origin for templates that come from non-loader sources
  66. # (e.g. strings)
  67. UNKNOWN_SOURCE = "<unknown source>"
  68. # Match BLOCK_TAG_*, VARIABLE_TAG_*, and COMMENT_TAG_* tags and capture the
  69. # entire tag, including start/end delimiters. Using re.compile() is faster
  70. # than instantiating SimpleLazyObject with _lazy_re_compile().
  71. tag_re = re.compile(r"({%.*?%}|{{.*?}}|{#.*?#})")
  72. logger = logging.getLogger("django.template")
  73. class TokenType(Enum):
  74. TEXT = 0
  75. VAR = 1
  76. BLOCK = 2
  77. COMMENT = 3
  78. class VariableDoesNotExist(Exception):
  79. def __init__(self, msg, params=()):
  80. self.msg = msg
  81. self.params = params
  82. def __str__(self):
  83. return self.msg % self.params
  84. class Origin:
  85. def __init__(self, name, template_name=None, loader=None):
  86. self.name = name
  87. self.template_name = template_name
  88. self.loader = loader
  89. def __str__(self):
  90. return self.name
  91. def __repr__(self):
  92. return "<%s name=%r>" % (self.__class__.__qualname__, self.name)
  93. def __eq__(self, other):
  94. return (
  95. isinstance(other, Origin)
  96. and self.name == other.name
  97. and self.loader == other.loader
  98. )
  99. @property
  100. def loader_name(self):
  101. if self.loader:
  102. return "%s.%s" % (
  103. self.loader.__module__,
  104. self.loader.__class__.__name__,
  105. )
  106. class Template:
  107. def __init__(self, template_string, origin=None, name=None, engine=None):
  108. # If Template is instantiated directly rather than from an Engine and
  109. # exactly one Django template engine is configured, use that engine.
  110. # This is required to preserve backwards-compatibility for direct use
  111. # e.g. Template('...').render(Context({...}))
  112. if engine is None:
  113. from .engine import Engine
  114. engine = Engine.get_default()
  115. if origin is None:
  116. origin = Origin(UNKNOWN_SOURCE)
  117. self.name = name
  118. self.origin = origin
  119. self.engine = engine
  120. self.source = str(template_string) # May be lazy.
  121. self.nodelist = self.compile_nodelist()
  122. def __repr__(self):
  123. return '<%s template_string="%s...">' % (
  124. self.__class__.__qualname__,
  125. self.source[:20].replace("\n", ""),
  126. )
  127. def _render(self, context):
  128. return self.nodelist.render(context)
  129. def render(self, context):
  130. "Display stage -- can be called many times"
  131. with context.render_context.push_state(self):
  132. if context.template is None:
  133. with context.bind_template(self):
  134. context.template_name = self.name
  135. return self._render(context)
  136. else:
  137. return self._render(context)
  138. def compile_nodelist(self):
  139. """
  140. Parse and compile the template source into a nodelist. If debug
  141. is True and an exception occurs during parsing, the exception is
  142. annotated with contextual line information where it occurred in the
  143. template source.
  144. """
  145. if self.engine.debug:
  146. lexer = DebugLexer(self.source)
  147. else:
  148. lexer = Lexer(self.source)
  149. tokens = lexer.tokenize()
  150. parser = Parser(
  151. tokens,
  152. self.engine.template_libraries,
  153. self.engine.template_builtins,
  154. self.origin,
  155. )
  156. try:
  157. nodelist = parser.parse()
  158. self.extra_data = parser.extra_data
  159. return nodelist
  160. except Exception as e:
  161. if self.engine.debug:
  162. e.template_debug = self.get_exception_info(e, e.token)
  163. raise
  164. def get_exception_info(self, exception, token):
  165. """
  166. Return a dictionary containing contextual line information of where
  167. the exception occurred in the template. The following information is
  168. provided:
  169. message
  170. The message of the exception raised.
  171. source_lines
  172. The lines before, after, and including the line the exception
  173. occurred on.
  174. line
  175. The line number the exception occurred on.
  176. before, during, after
  177. The line the exception occurred on split into three parts:
  178. 1. The content before the token that raised the error.
  179. 2. The token that raised the error.
  180. 3. The content after the token that raised the error.
  181. total
  182. The number of lines in source_lines.
  183. top
  184. The line number where source_lines starts.
  185. bottom
  186. The line number where source_lines ends.
  187. start
  188. The start position of the token in the template source.
  189. end
  190. The end position of the token in the template source.
  191. """
  192. start, end = token.position
  193. context_lines = 10
  194. line = 0
  195. upto = 0
  196. source_lines = []
  197. before = during = after = ""
  198. for num, next in enumerate(linebreak_iter(self.source)):
  199. if start >= upto and end <= next:
  200. line = num
  201. before = escape(self.source[upto:start])
  202. during = escape(self.source[start:end])
  203. after = escape(self.source[end:next])
  204. source_lines.append((num, escape(self.source[upto:next])))
  205. upto = next
  206. total = len(source_lines)
  207. top = max(1, line - context_lines)
  208. bottom = min(total, line + 1 + context_lines)
  209. # In some rare cases exc_value.args can be empty or an invalid
  210. # string.
  211. try:
  212. message = str(exception.args[0])
  213. except (IndexError, UnicodeDecodeError):
  214. message = "(Could not get exception message)"
  215. return {
  216. "message": message,
  217. "source_lines": source_lines[top:bottom],
  218. "before": before,
  219. "during": during,
  220. "after": after,
  221. "top": top,
  222. "bottom": bottom,
  223. "total": total,
  224. "line": line,
  225. "name": self.origin.name,
  226. "start": start,
  227. "end": end,
  228. }
  229. def linebreak_iter(template_source):
  230. yield 0
  231. p = template_source.find("\n")
  232. while p >= 0:
  233. yield p + 1
  234. p = template_source.find("\n", p + 1)
  235. yield len(template_source) + 1
  236. class Token:
  237. def __init__(self, token_type, contents, position=None, lineno=None):
  238. """
  239. A token representing a string from the template.
  240. token_type
  241. A TokenType, either .TEXT, .VAR, .BLOCK, or .COMMENT.
  242. contents
  243. The token source string.
  244. position
  245. An optional tuple containing the start and end index of the token
  246. in the template source. This is used for traceback information
  247. when debug is on.
  248. lineno
  249. The line number the token appears on in the template source.
  250. This is used for traceback information and gettext files.
  251. """
  252. self.token_type = token_type
  253. self.contents = contents
  254. self.lineno = lineno
  255. self.position = position
  256. def __repr__(self):
  257. token_name = self.token_type.name.capitalize()
  258. return '<%s token: "%s...">' % (
  259. token_name,
  260. self.contents[:20].replace("\n", ""),
  261. )
  262. def split_contents(self):
  263. split = []
  264. bits = smart_split(self.contents)
  265. for bit in bits:
  266. # Handle translation-marked template pieces
  267. if bit.startswith(('_("', "_('")):
  268. sentinel = bit[2] + ")"
  269. trans_bit = [bit]
  270. while not bit.endswith(sentinel):
  271. bit = next(bits)
  272. trans_bit.append(bit)
  273. bit = " ".join(trans_bit)
  274. split.append(bit)
  275. return split
  276. class Lexer:
  277. def __init__(self, template_string):
  278. self.template_string = template_string
  279. self.verbatim = False
  280. def __repr__(self):
  281. return '<%s template_string="%s...", verbatim=%s>' % (
  282. self.__class__.__qualname__,
  283. self.template_string[:20].replace("\n", ""),
  284. self.verbatim,
  285. )
  286. def tokenize(self):
  287. """
  288. Return a list of tokens from a given template_string.
  289. """
  290. in_tag = False
  291. lineno = 1
  292. result = []
  293. for token_string in tag_re.split(self.template_string):
  294. if token_string:
  295. result.append(self.create_token(token_string, None, lineno, in_tag))
  296. lineno += token_string.count("\n")
  297. in_tag = not in_tag
  298. return result
  299. def create_token(self, token_string, position, lineno, in_tag):
  300. """
  301. Convert the given token string into a new Token object and return it.
  302. If in_tag is True, we are processing something that matched a tag,
  303. otherwise it should be treated as a literal string.
  304. """
  305. if in_tag:
  306. # The [0:2] and [2:-2] ranges below strip off *_TAG_START and
  307. # *_TAG_END. The 2's are hard-coded for performance. Using
  308. # len(BLOCK_TAG_START) would permit BLOCK_TAG_START to be
  309. # different, but it's not likely that the TAG_START values will
  310. # change anytime soon.
  311. token_start = token_string[0:2]
  312. if token_start == BLOCK_TAG_START:
  313. content = token_string[2:-2].strip()
  314. if self.verbatim:
  315. # Then a verbatim block is being processed.
  316. if content != self.verbatim:
  317. return Token(TokenType.TEXT, token_string, position, lineno)
  318. # Otherwise, the current verbatim block is ending.
  319. self.verbatim = False
  320. elif content[:9] in ("verbatim", "verbatim "):
  321. # Then a verbatim block is starting.
  322. self.verbatim = "end%s" % content
  323. return Token(TokenType.BLOCK, content, position, lineno)
  324. if not self.verbatim:
  325. content = token_string[2:-2].strip()
  326. if token_start == VARIABLE_TAG_START:
  327. return Token(TokenType.VAR, content, position, lineno)
  328. # BLOCK_TAG_START was handled above.
  329. assert token_start == COMMENT_TAG_START
  330. return Token(TokenType.COMMENT, content, position, lineno)
  331. return Token(TokenType.TEXT, token_string, position, lineno)
  332. class DebugLexer(Lexer):
  333. def _tag_re_split_positions(self):
  334. last = 0
  335. for match in tag_re.finditer(self.template_string):
  336. start, end = match.span()
  337. yield last, start
  338. yield start, end
  339. last = end
  340. yield last, len(self.template_string)
  341. # This parallels the use of tag_re.split() in Lexer.tokenize().
  342. def _tag_re_split(self):
  343. for position in self._tag_re_split_positions():
  344. yield self.template_string[slice(*position)], position
  345. def tokenize(self):
  346. """
  347. Split a template string into tokens and annotates each token with its
  348. start and end position in the source. This is slower than the default
  349. lexer so only use it when debug is True.
  350. """
  351. # For maintainability, it is helpful if the implementation below can
  352. # continue to closely parallel Lexer.tokenize()'s implementation.
  353. in_tag = False
  354. lineno = 1
  355. result = []
  356. for token_string, position in self._tag_re_split():
  357. if token_string:
  358. result.append(self.create_token(token_string, position, lineno, in_tag))
  359. lineno += token_string.count("\n")
  360. in_tag = not in_tag
  361. return result
  362. class Parser:
  363. def __init__(self, tokens, libraries=None, builtins=None, origin=None):
  364. # Reverse the tokens so delete_first_token(), prepend_token(), and
  365. # next_token() can operate at the end of the list in constant time.
  366. self.tokens = list(reversed(tokens))
  367. self.tags = {}
  368. self.filters = {}
  369. self.command_stack = []
  370. # Custom template tags may store additional data on the parser that
  371. # will be made available on the template instance. Library authors
  372. # should use a key to namespace any added data. The 'django' namespace
  373. # is reserved for internal use.
  374. self.extra_data = {}
  375. if libraries is None:
  376. libraries = {}
  377. if builtins is None:
  378. builtins = []
  379. self.libraries = libraries
  380. for builtin in builtins:
  381. self.add_library(builtin)
  382. self.origin = origin
  383. def __repr__(self):
  384. return "<%s tokens=%r>" % (self.__class__.__qualname__, self.tokens)
  385. def parse(self, parse_until=None):
  386. """
  387. Iterate through the parser tokens and compiles each one into a node.
  388. If parse_until is provided, parsing will stop once one of the
  389. specified tokens has been reached. This is formatted as a list of
  390. tokens, e.g. ['elif', 'else', 'endif']. If no matching token is
  391. reached, raise an exception with the unclosed block tag details.
  392. """
  393. if parse_until is None:
  394. parse_until = []
  395. nodelist = NodeList()
  396. while self.tokens:
  397. token = self.next_token()
  398. # Use the raw values here for TokenType.* for a tiny performance boost.
  399. token_type = token.token_type.value
  400. if token_type == 0: # TokenType.TEXT
  401. self.extend_nodelist(nodelist, TextNode(token.contents), token)
  402. elif token_type == 1: # TokenType.VAR
  403. if not token.contents:
  404. raise self.error(
  405. token, "Empty variable tag on line %d" % token.lineno
  406. )
  407. try:
  408. filter_expression = self.compile_filter(token.contents)
  409. except TemplateSyntaxError as e:
  410. raise self.error(token, e)
  411. var_node = VariableNode(filter_expression)
  412. self.extend_nodelist(nodelist, var_node, token)
  413. elif token_type == 2: # TokenType.BLOCK
  414. try:
  415. command = token.contents.split()[0]
  416. except IndexError:
  417. raise self.error(token, "Empty block tag on line %d" % token.lineno)
  418. if command in parse_until:
  419. # A matching token has been reached. Return control to
  420. # the caller. Put the token back on the token list so the
  421. # caller knows where it terminated.
  422. self.prepend_token(token)
  423. return nodelist
  424. # Add the token to the command stack. This is used for error
  425. # messages if further parsing fails due to an unclosed block
  426. # tag.
  427. self.command_stack.append((command, token))
  428. # Get the tag callback function from the ones registered with
  429. # the parser.
  430. try:
  431. compile_func = self.tags[command]
  432. except KeyError:
  433. self.invalid_block_tag(token, command, parse_until)
  434. # Compile the callback into a node object and add it to
  435. # the node list.
  436. try:
  437. compiled_result = compile_func(self, token)
  438. except Exception as e:
  439. raise self.error(token, e)
  440. self.extend_nodelist(nodelist, compiled_result, token)
  441. # Compile success. Remove the token from the command stack.
  442. self.command_stack.pop()
  443. if parse_until:
  444. self.unclosed_block_tag(parse_until)
  445. return nodelist
  446. def skip_past(self, endtag):
  447. while self.tokens:
  448. token = self.next_token()
  449. if token.token_type == TokenType.BLOCK and token.contents == endtag:
  450. return
  451. self.unclosed_block_tag([endtag])
  452. def extend_nodelist(self, nodelist, node, token):
  453. # Check that non-text nodes don't appear before an extends tag.
  454. if node.must_be_first and nodelist.contains_nontext:
  455. raise self.error(
  456. token,
  457. "%r must be the first tag in the template." % node,
  458. )
  459. if not isinstance(node, TextNode):
  460. nodelist.contains_nontext = True
  461. # Set origin and token here since we can't modify the node __init__()
  462. # method.
  463. node.token = token
  464. node.origin = self.origin
  465. nodelist.append(node)
  466. def error(self, token, e):
  467. """
  468. Return an exception annotated with the originating token. Since the
  469. parser can be called recursively, check if a token is already set. This
  470. ensures the innermost token is highlighted if an exception occurs,
  471. e.g. a compile error within the body of an if statement.
  472. """
  473. if not isinstance(e, Exception):
  474. e = TemplateSyntaxError(e)
  475. if not hasattr(e, "token"):
  476. e.token = token
  477. return e
  478. def invalid_block_tag(self, token, command, parse_until=None):
  479. if parse_until:
  480. raise self.error(
  481. token,
  482. "Invalid block tag on line %d: '%s', expected %s. Did you "
  483. "forget to register or load this tag?"
  484. % (
  485. token.lineno,
  486. command,
  487. get_text_list(["'%s'" % p for p in parse_until], "or"),
  488. ),
  489. )
  490. raise self.error(
  491. token,
  492. "Invalid block tag on line %d: '%s'. Did you forget to register "
  493. "or load this tag?" % (token.lineno, command),
  494. )
  495. def unclosed_block_tag(self, parse_until):
  496. command, token = self.command_stack.pop()
  497. msg = "Unclosed tag on line %d: '%s'. Looking for one of: %s." % (
  498. token.lineno,
  499. command,
  500. ", ".join(parse_until),
  501. )
  502. raise self.error(token, msg)
  503. def next_token(self):
  504. return self.tokens.pop()
  505. def prepend_token(self, token):
  506. self.tokens.append(token)
  507. def delete_first_token(self):
  508. del self.tokens[-1]
  509. def add_library(self, lib):
  510. self.tags.update(lib.tags)
  511. self.filters.update(lib.filters)
  512. def compile_filter(self, token):
  513. """
  514. Convenient wrapper for FilterExpression
  515. """
  516. return FilterExpression(token, self)
  517. def find_filter(self, filter_name):
  518. if filter_name in self.filters:
  519. return self.filters[filter_name]
  520. else:
  521. raise TemplateSyntaxError("Invalid filter: '%s'" % filter_name)
  522. # This only matches constant *strings* (things in quotes or marked for
  523. # translation). Numbers are treated as variables for implementation reasons
  524. # (so that they retain their type when passed to filters).
  525. constant_string = r"""
  526. (?:%(i18n_open)s%(strdq)s%(i18n_close)s|
  527. %(i18n_open)s%(strsq)s%(i18n_close)s|
  528. %(strdq)s|
  529. %(strsq)s)
  530. """ % {
  531. "strdq": r'"[^"\\]*(?:\\.[^"\\]*)*"', # double-quoted string
  532. "strsq": r"'[^'\\]*(?:\\.[^'\\]*)*'", # single-quoted string
  533. "i18n_open": re.escape("_("),
  534. "i18n_close": re.escape(")"),
  535. }
  536. constant_string = constant_string.replace("\n", "")
  537. filter_raw_string = r"""
  538. ^(?P<constant>%(constant)s)|
  539. ^(?P<var>[%(var_chars)s]+|%(num)s)|
  540. (?:\s*%(filter_sep)s\s*
  541. (?P<filter_name>\w+)
  542. (?:%(arg_sep)s
  543. (?:
  544. (?P<constant_arg>%(constant)s)|
  545. (?P<var_arg>[%(var_chars)s]+|%(num)s)
  546. )
  547. )?
  548. )""" % {
  549. "constant": constant_string,
  550. "num": r"[-+.]?\d[\d.e]*",
  551. "var_chars": r"\w\.",
  552. "filter_sep": re.escape(FILTER_SEPARATOR),
  553. "arg_sep": re.escape(FILTER_ARGUMENT_SEPARATOR),
  554. }
  555. filter_re = _lazy_re_compile(filter_raw_string, re.VERBOSE)
  556. class FilterExpression:
  557. """
  558. Parse a variable token and its optional filters (all as a single string),
  559. and return a list of tuples of the filter name and arguments.
  560. Sample::
  561. >>> token = 'variable|default:"Default value"|date:"Y-m-d"'
  562. >>> p = Parser('')
  563. >>> fe = FilterExpression(token, p)
  564. >>> len(fe.filters)
  565. 2
  566. >>> fe.var
  567. <Variable: 'variable'>
  568. """
  569. __slots__ = ("token", "filters", "var", "is_var")
  570. def __init__(self, token, parser):
  571. self.token = token
  572. matches = filter_re.finditer(token)
  573. var_obj = None
  574. filters = []
  575. upto = 0
  576. for match in matches:
  577. start = match.start()
  578. if upto != start:
  579. raise TemplateSyntaxError(
  580. "Could not parse some characters: "
  581. "%s|%s|%s" % (token[:upto], token[upto:start], token[start:])
  582. )
  583. if var_obj is None:
  584. if constant := match["constant"]:
  585. try:
  586. var_obj = Variable(constant).resolve({})
  587. except VariableDoesNotExist:
  588. var_obj = None
  589. elif (var := match["var"]) is None:
  590. raise TemplateSyntaxError(
  591. "Could not find variable at start of %s." % token
  592. )
  593. else:
  594. var_obj = Variable(var)
  595. else:
  596. filter_name = match["filter_name"]
  597. args = []
  598. if constant_arg := match["constant_arg"]:
  599. args.append((False, Variable(constant_arg).resolve({})))
  600. elif var_arg := match["var_arg"]:
  601. args.append((True, Variable(var_arg)))
  602. filter_func = parser.find_filter(filter_name)
  603. self.args_check(filter_name, filter_func, args)
  604. filters.append((filter_func, args))
  605. upto = match.end()
  606. if upto != len(token):
  607. raise TemplateSyntaxError(
  608. "Could not parse the remainder: '%s' "
  609. "from '%s'" % (token[upto:], token)
  610. )
  611. self.filters = filters
  612. self.var = var_obj
  613. self.is_var = isinstance(var_obj, Variable)
  614. def resolve(self, context, ignore_failures=False):
  615. if self.is_var:
  616. try:
  617. obj = self.var.resolve(context)
  618. except VariableDoesNotExist:
  619. if ignore_failures:
  620. obj = None
  621. else:
  622. string_if_invalid = context.template.engine.string_if_invalid
  623. if string_if_invalid:
  624. if "%s" in string_if_invalid:
  625. return string_if_invalid % self.var
  626. else:
  627. return string_if_invalid
  628. else:
  629. obj = string_if_invalid
  630. else:
  631. obj = self.var
  632. for func, args in self.filters:
  633. arg_vals = []
  634. for lookup, arg in args:
  635. if not lookup:
  636. arg_vals.append(mark_safe(arg))
  637. else:
  638. arg_vals.append(arg.resolve(context))
  639. if getattr(func, "expects_localtime", False):
  640. obj = template_localtime(obj, context.use_tz)
  641. if getattr(func, "needs_autoescape", False):
  642. new_obj = func(obj, autoescape=context.autoescape, *arg_vals)
  643. else:
  644. new_obj = func(obj, *arg_vals)
  645. if getattr(func, "is_safe", False) and isinstance(obj, SafeData):
  646. obj = mark_safe(new_obj)
  647. else:
  648. obj = new_obj
  649. return obj
  650. def args_check(name, func, provided):
  651. provided = list(provided)
  652. # First argument, filter input, is implied.
  653. plen = len(provided) + 1
  654. # Check to see if a decorator is providing the real function.
  655. func = inspect.unwrap(func)
  656. args, _, _, defaults, _, _, _ = inspect.getfullargspec(func)
  657. alen = len(args)
  658. dlen = len(defaults or [])
  659. # Not enough OR Too many
  660. if plen < (alen - dlen) or plen > alen:
  661. raise TemplateSyntaxError(
  662. "%s requires %d arguments, %d provided" % (name, alen - dlen, plen)
  663. )
  664. return True
  665. args_check = staticmethod(args_check)
  666. def __str__(self):
  667. return self.token
  668. def __repr__(self):
  669. return "<%s %r>" % (self.__class__.__qualname__, self.token)
  670. class Variable:
  671. """
  672. A template variable, resolvable against a given context. The variable may
  673. be a hard-coded string (if it begins and ends with single or double quote
  674. marks)::
  675. >>> c = {'article': {'section':'News'}}
  676. >>> Variable('article.section').resolve(c)
  677. 'News'
  678. >>> Variable('article').resolve(c)
  679. {'section': 'News'}
  680. >>> class AClass: pass
  681. >>> c = AClass()
  682. >>> c.article = AClass()
  683. >>> c.article.section = 'News'
  684. (The example assumes VARIABLE_ATTRIBUTE_SEPARATOR is '.')
  685. """
  686. __slots__ = ("var", "literal", "lookups", "translate", "message_context")
  687. def __init__(self, var):
  688. self.var = var
  689. self.literal = None
  690. self.lookups = None
  691. self.translate = False
  692. self.message_context = None
  693. if not isinstance(var, str):
  694. raise TypeError("Variable must be a string or number, got %s" % type(var))
  695. try:
  696. # First try to treat this variable as a number.
  697. #
  698. # Note that this could cause an OverflowError here that we're not
  699. # catching. Since this should only happen at compile time, that's
  700. # probably OK.
  701. # Try to interpret values containing a period or an 'e'/'E'
  702. # (possibly scientific notation) as a float; otherwise, try int.
  703. if "." in var or "e" in var.lower():
  704. self.literal = float(var)
  705. # "2." is invalid
  706. if var[-1] == ".":
  707. raise ValueError
  708. else:
  709. self.literal = int(var)
  710. except ValueError:
  711. # A ValueError means that the variable isn't a number.
  712. if var[0:2] == "_(" and var[-1] == ")":
  713. # The result of the lookup should be translated at rendering
  714. # time.
  715. self.translate = True
  716. var = var[2:-1]
  717. # If it's wrapped with quotes (single or double), then
  718. # we're also dealing with a literal.
  719. try:
  720. self.literal = mark_safe(unescape_string_literal(var))
  721. except ValueError:
  722. # Otherwise we'll set self.lookups so that resolve() knows we're
  723. # dealing with a bonafide variable
  724. if VARIABLE_ATTRIBUTE_SEPARATOR + "_" in var or var[0] == "_":
  725. raise TemplateSyntaxError(
  726. "Variables and attributes may "
  727. "not begin with underscores: '%s'" % var
  728. )
  729. self.lookups = tuple(var.split(VARIABLE_ATTRIBUTE_SEPARATOR))
  730. def resolve(self, context):
  731. """Resolve this variable against a given context."""
  732. if self.lookups is not None:
  733. # We're dealing with a variable that needs to be resolved
  734. value = self._resolve_lookup(context)
  735. else:
  736. # We're dealing with a literal, so it's already been "resolved"
  737. value = self.literal
  738. if self.translate:
  739. is_safe = isinstance(value, SafeData)
  740. msgid = value.replace("%", "%%")
  741. msgid = mark_safe(msgid) if is_safe else msgid
  742. if self.message_context:
  743. return pgettext_lazy(self.message_context, msgid)
  744. else:
  745. return gettext_lazy(msgid)
  746. return value
  747. def __repr__(self):
  748. return "<%s: %r>" % (self.__class__.__name__, self.var)
  749. def __str__(self):
  750. return self.var
  751. def _resolve_lookup(self, context):
  752. """
  753. Perform resolution of a real variable (i.e. not a literal) against the
  754. given context.
  755. As indicated by the method's name, this method is an implementation
  756. detail and shouldn't be called by external code. Use Variable.resolve()
  757. instead.
  758. """
  759. current = context
  760. try: # catch-all for silent variable failures
  761. for bit in self.lookups:
  762. try: # dictionary lookup
  763. current = current[bit]
  764. # ValueError/IndexError are for numpy.array lookup on
  765. # numpy < 1.9 and 1.9+ respectively
  766. except (TypeError, AttributeError, KeyError, ValueError, IndexError):
  767. try: # attribute lookup
  768. # Don't return class attributes if the class is the context:
  769. if isinstance(current, BaseContext) and getattr(
  770. type(current), bit
  771. ):
  772. raise AttributeError
  773. current = getattr(current, bit)
  774. except (TypeError, AttributeError):
  775. # Reraise if the exception was raised by a @property
  776. if not isinstance(current, BaseContext) and bit in dir(current):
  777. raise
  778. try: # list-index lookup
  779. current = current[int(bit)]
  780. except (
  781. IndexError, # list index out of range
  782. ValueError, # invalid literal for int()
  783. KeyError, # current is a dict without `int(bit)` key
  784. TypeError,
  785. ): # unsubscriptable object
  786. raise VariableDoesNotExist(
  787. "Failed lookup for key [%s] in %r",
  788. (bit, current),
  789. ) # missing attribute
  790. if callable(current):
  791. if getattr(current, "do_not_call_in_templates", False):
  792. pass
  793. elif getattr(current, "alters_data", False):
  794. current = context.template.engine.string_if_invalid
  795. else:
  796. try: # method call (assuming no args required)
  797. current = current()
  798. except TypeError:
  799. try:
  800. signature = inspect.signature(current)
  801. except ValueError: # No signature found.
  802. current = context.template.engine.string_if_invalid
  803. else:
  804. try:
  805. signature.bind()
  806. except TypeError: # Arguments *were* required.
  807. # Invalid method call.
  808. current = context.template.engine.string_if_invalid
  809. else:
  810. raise
  811. except Exception as e:
  812. template_name = getattr(context, "template_name", None) or "unknown"
  813. logger.debug(
  814. "Exception while resolving variable '%s' in template '%s'.",
  815. bit,
  816. template_name,
  817. exc_info=True,
  818. )
  819. if getattr(e, "silent_variable_failure", False):
  820. current = context.template.engine.string_if_invalid
  821. else:
  822. raise
  823. return current
  824. class Node:
  825. # Set this to True for nodes that must be first in the template (although
  826. # they can be preceded by text nodes.
  827. must_be_first = False
  828. child_nodelists = ("nodelist",)
  829. token = None
  830. def render(self, context):
  831. """
  832. Return the node rendered as a string.
  833. """
  834. pass
  835. def render_annotated(self, context):
  836. """
  837. Render the node. If debug is True and an exception occurs during
  838. rendering, the exception is annotated with contextual line information
  839. where it occurred in the template. For internal usage this method is
  840. preferred over using the render method directly.
  841. """
  842. try:
  843. return self.render(context)
  844. except Exception as e:
  845. if context.template.engine.debug:
  846. # Store the actual node that caused the exception.
  847. if not hasattr(e, "_culprit_node"):
  848. e._culprit_node = self
  849. if (
  850. not hasattr(e, "template_debug")
  851. and context.render_context.template.origin == e._culprit_node.origin
  852. ):
  853. e.template_debug = (
  854. context.render_context.template.get_exception_info(
  855. e,
  856. e._culprit_node.token,
  857. )
  858. )
  859. raise
  860. def get_nodes_by_type(self, nodetype):
  861. """
  862. Return a list of all nodes (within this node and its nodelist)
  863. of the given type
  864. """
  865. nodes = []
  866. if isinstance(self, nodetype):
  867. nodes.append(self)
  868. for attr in self.child_nodelists:
  869. nodelist = getattr(self, attr, None)
  870. if nodelist:
  871. nodes.extend(nodelist.get_nodes_by_type(nodetype))
  872. return nodes
  873. class NodeList(list):
  874. # Set to True the first time a non-TextNode is inserted by
  875. # extend_nodelist().
  876. contains_nontext = False
  877. def render(self, context):
  878. return SafeString("".join([node.render_annotated(context) for node in self]))
  879. def get_nodes_by_type(self, nodetype):
  880. "Return a list of all nodes of the given type"
  881. nodes = []
  882. for node in self:
  883. nodes.extend(node.get_nodes_by_type(nodetype))
  884. return nodes
  885. class TextNode(Node):
  886. child_nodelists = ()
  887. def __init__(self, s):
  888. self.s = s
  889. def __repr__(self):
  890. return "<%s: %r>" % (self.__class__.__name__, self.s[:25])
  891. def render(self, context):
  892. return self.s
  893. def render_annotated(self, context):
  894. """
  895. Return the given value.
  896. The default implementation of this method handles exceptions raised
  897. during rendering, which is not necessary for text nodes.
  898. """
  899. return self.s
  900. def render_value_in_context(value, context):
  901. """
  902. Convert any value to a string to become part of a rendered template. This
  903. means escaping, if required, and conversion to a string. If value is a
  904. string, it's expected to already be translated.
  905. """
  906. value = template_localtime(value, use_tz=context.use_tz)
  907. value = localize(value, use_l10n=context.use_l10n)
  908. if context.autoescape:
  909. if not issubclass(type(value), str):
  910. value = str(value)
  911. return conditional_escape(value)
  912. else:
  913. return str(value)
  914. class VariableNode(Node):
  915. child_nodelists = ()
  916. def __init__(self, filter_expression):
  917. self.filter_expression = filter_expression
  918. def __repr__(self):
  919. return "<Variable Node: %s>" % self.filter_expression
  920. def render(self, context):
  921. try:
  922. output = self.filter_expression.resolve(context)
  923. except UnicodeDecodeError:
  924. # Unicode conversion can fail sometimes for reasons out of our
  925. # control (e.g. exception rendering). In that case, we fail
  926. # quietly.
  927. return ""
  928. return render_value_in_context(output, context)
  929. # Regex for token keyword arguments
  930. kwarg_re = _lazy_re_compile(r"(?:(\w+)=)?(.+)")
  931. def token_kwargs(bits, parser, support_legacy=False):
  932. """
  933. Parse token keyword arguments and return a dictionary of the arguments
  934. retrieved from the ``bits`` token list.
  935. `bits` is a list containing the remainder of the token (split by spaces)
  936. that is to be checked for arguments. Valid arguments are removed from this
  937. list.
  938. `support_legacy` - if True, the legacy format ``1 as foo`` is accepted.
  939. Otherwise, only the standard ``foo=1`` format is allowed.
  940. There is no requirement for all remaining token ``bits`` to be keyword
  941. arguments, so return the dictionary as soon as an invalid argument format
  942. is reached.
  943. """
  944. if not bits:
  945. return {}
  946. match = kwarg_re.match(bits[0])
  947. kwarg_format = match and match[1]
  948. if not kwarg_format:
  949. if not support_legacy:
  950. return {}
  951. if len(bits) < 3 or bits[1] != "as":
  952. return {}
  953. kwargs = {}
  954. while bits:
  955. if kwarg_format:
  956. match = kwarg_re.match(bits[0])
  957. if not match or not match[1]:
  958. return kwargs
  959. key, value = match.groups()
  960. del bits[:1]
  961. else:
  962. if len(bits) < 3 or bits[1] != "as":
  963. return kwargs
  964. key, value = bits[2], bits[0]
  965. del bits[:3]
  966. kwargs[key] = parser.compile_filter(value)
  967. if bits and not kwarg_format:
  968. if bits[0] != "and":
  969. return kwargs
  970. del bits[:1]
  971. return kwargs