base.py 44 KB

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