Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

base.py 39KB

1 year ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  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 __iter__(self):
  123. for node in self.nodelist:
  124. yield from node
  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. return parser.parse()
  161. except Exception as e:
  162. if self.engine.debug:
  163. e.template_debug = self.get_exception_info(e, e.token)
  164. raise
  165. def get_exception_info(self, exception, token):
  166. """
  167. Return a dictionary containing contextual line information of where
  168. the exception occurred in the template. The following information is
  169. provided:
  170. message
  171. The message of the exception raised.
  172. source_lines
  173. The lines before, after, and including the line the exception
  174. occurred on.
  175. line
  176. The line number the exception occurred on.
  177. before, during, after
  178. The line the exception occurred on split into three parts:
  179. 1. The content before the token that raised the error.
  180. 2. The token that raised the error.
  181. 3. The content after the token that raised the error.
  182. total
  183. The number of lines in source_lines.
  184. top
  185. The line number where source_lines starts.
  186. bottom
  187. The line number where source_lines ends.
  188. start
  189. The start position of the token in the template source.
  190. end
  191. The end position of the token in the template source.
  192. """
  193. start, end = token.position
  194. context_lines = 10
  195. line = 0
  196. upto = 0
  197. source_lines = []
  198. before = during = after = ""
  199. for num, next in enumerate(linebreak_iter(self.source)):
  200. if start >= upto and end <= next:
  201. line = num
  202. before = escape(self.source[upto:start])
  203. during = escape(self.source[start:end])
  204. after = escape(self.source[end:next])
  205. source_lines.append((num, escape(self.source[upto:next])))
  206. upto = next
  207. total = len(source_lines)
  208. top = max(1, line - context_lines)
  209. bottom = min(total, line + 1 + context_lines)
  210. # In some rare cases exc_value.args can be empty or an invalid
  211. # string.
  212. try:
  213. message = str(exception.args[0])
  214. except (IndexError, UnicodeDecodeError):
  215. message = "(Could not get exception message)"
  216. return {
  217. "message": message,
  218. "source_lines": source_lines[top:bottom],
  219. "before": before,
  220. "during": during,
  221. "after": after,
  222. "top": top,
  223. "bottom": bottom,
  224. "total": total,
  225. "line": line,
  226. "name": self.origin.name,
  227. "start": start,
  228. "end": end,
  229. }
  230. def linebreak_iter(template_source):
  231. yield 0
  232. p = template_source.find("\n")
  233. while p >= 0:
  234. yield p + 1
  235. p = template_source.find("\n", p + 1)
  236. yield len(template_source) + 1
  237. class Token:
  238. def __init__(self, token_type, contents, position=None, lineno=None):
  239. """
  240. A token representing a string from the template.
  241. token_type
  242. A TokenType, either .TEXT, .VAR, .BLOCK, or .COMMENT.
  243. contents
  244. The token source string.
  245. position
  246. An optional tuple containing the start and end index of the token
  247. in the template source. This is used for traceback information
  248. when debug is on.
  249. lineno
  250. The line number the token appears on in the template source.
  251. This is used for traceback information and gettext files.
  252. """
  253. self.token_type, self.contents = token_type, 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. if libraries is None:
  371. libraries = {}
  372. if builtins is None:
  373. builtins = []
  374. self.libraries = libraries
  375. for builtin in builtins:
  376. self.add_library(builtin)
  377. self.origin = origin
  378. def __repr__(self):
  379. return "<%s tokens=%r>" % (self.__class__.__qualname__, self.tokens)
  380. def parse(self, parse_until=None):
  381. """
  382. Iterate through the parser tokens and compiles each one into a node.
  383. If parse_until is provided, parsing will stop once one of the
  384. specified tokens has been reached. This is formatted as a list of
  385. tokens, e.g. ['elif', 'else', 'endif']. If no matching token is
  386. reached, raise an exception with the unclosed block tag details.
  387. """
  388. if parse_until is None:
  389. parse_until = []
  390. nodelist = NodeList()
  391. while self.tokens:
  392. token = self.next_token()
  393. # Use the raw values here for TokenType.* for a tiny performance boost.
  394. token_type = token.token_type.value
  395. if token_type == 0: # TokenType.TEXT
  396. self.extend_nodelist(nodelist, TextNode(token.contents), token)
  397. elif token_type == 1: # TokenType.VAR
  398. if not token.contents:
  399. raise self.error(
  400. token, "Empty variable tag on line %d" % token.lineno
  401. )
  402. try:
  403. filter_expression = self.compile_filter(token.contents)
  404. except TemplateSyntaxError as e:
  405. raise self.error(token, e)
  406. var_node = VariableNode(filter_expression)
  407. self.extend_nodelist(nodelist, var_node, token)
  408. elif token_type == 2: # TokenType.BLOCK
  409. try:
  410. command = token.contents.split()[0]
  411. except IndexError:
  412. raise self.error(token, "Empty block tag on line %d" % token.lineno)
  413. if command in parse_until:
  414. # A matching token has been reached. Return control to
  415. # the caller. Put the token back on the token list so the
  416. # caller knows where it terminated.
  417. self.prepend_token(token)
  418. return nodelist
  419. # Add the token to the command stack. This is used for error
  420. # messages if further parsing fails due to an unclosed block
  421. # tag.
  422. self.command_stack.append((command, token))
  423. # Get the tag callback function from the ones registered with
  424. # the parser.
  425. try:
  426. compile_func = self.tags[command]
  427. except KeyError:
  428. self.invalid_block_tag(token, command, parse_until)
  429. # Compile the callback into a node object and add it to
  430. # the node list.
  431. try:
  432. compiled_result = compile_func(self, token)
  433. except Exception as e:
  434. raise self.error(token, e)
  435. self.extend_nodelist(nodelist, compiled_result, token)
  436. # Compile success. Remove the token from the command stack.
  437. self.command_stack.pop()
  438. if parse_until:
  439. self.unclosed_block_tag(parse_until)
  440. return nodelist
  441. def skip_past(self, endtag):
  442. while self.tokens:
  443. token = self.next_token()
  444. if token.token_type == TokenType.BLOCK and token.contents == endtag:
  445. return
  446. self.unclosed_block_tag([endtag])
  447. def extend_nodelist(self, nodelist, node, token):
  448. # Check that non-text nodes don't appear before an extends tag.
  449. if node.must_be_first and nodelist.contains_nontext:
  450. raise self.error(
  451. token,
  452. "%r must be the first tag in the template." % node,
  453. )
  454. if not isinstance(node, TextNode):
  455. nodelist.contains_nontext = True
  456. # Set origin and token here since we can't modify the node __init__()
  457. # method.
  458. node.token = token
  459. node.origin = self.origin
  460. nodelist.append(node)
  461. def error(self, token, e):
  462. """
  463. Return an exception annotated with the originating token. Since the
  464. parser can be called recursively, check if a token is already set. This
  465. ensures the innermost token is highlighted if an exception occurs,
  466. e.g. a compile error within the body of an if statement.
  467. """
  468. if not isinstance(e, Exception):
  469. e = TemplateSyntaxError(e)
  470. if not hasattr(e, "token"):
  471. e.token = token
  472. return e
  473. def invalid_block_tag(self, token, command, parse_until=None):
  474. if parse_until:
  475. raise self.error(
  476. token,
  477. "Invalid block tag on line %d: '%s', expected %s. Did you "
  478. "forget to register or load this tag?"
  479. % (
  480. token.lineno,
  481. command,
  482. get_text_list(["'%s'" % p for p in parse_until], "or"),
  483. ),
  484. )
  485. raise self.error(
  486. token,
  487. "Invalid block tag on line %d: '%s'. Did you forget to register "
  488. "or load this tag?" % (token.lineno, command),
  489. )
  490. def unclosed_block_tag(self, parse_until):
  491. command, token = self.command_stack.pop()
  492. msg = "Unclosed tag on line %d: '%s'. Looking for one of: %s." % (
  493. token.lineno,
  494. command,
  495. ", ".join(parse_until),
  496. )
  497. raise self.error(token, msg)
  498. def next_token(self):
  499. return self.tokens.pop()
  500. def prepend_token(self, token):
  501. self.tokens.append(token)
  502. def delete_first_token(self):
  503. del self.tokens[-1]
  504. def add_library(self, lib):
  505. self.tags.update(lib.tags)
  506. self.filters.update(lib.filters)
  507. def compile_filter(self, token):
  508. """
  509. Convenient wrapper for FilterExpression
  510. """
  511. return FilterExpression(token, self)
  512. def find_filter(self, filter_name):
  513. if filter_name in self.filters:
  514. return self.filters[filter_name]
  515. else:
  516. raise TemplateSyntaxError("Invalid filter: '%s'" % filter_name)
  517. # This only matches constant *strings* (things in quotes or marked for
  518. # translation). Numbers are treated as variables for implementation reasons
  519. # (so that they retain their type when passed to filters).
  520. constant_string = r"""
  521. (?:%(i18n_open)s%(strdq)s%(i18n_close)s|
  522. %(i18n_open)s%(strsq)s%(i18n_close)s|
  523. %(strdq)s|
  524. %(strsq)s)
  525. """ % {
  526. "strdq": r'"[^"\\]*(?:\\.[^"\\]*)*"', # double-quoted string
  527. "strsq": r"'[^'\\]*(?:\\.[^'\\]*)*'", # single-quoted string
  528. "i18n_open": re.escape("_("),
  529. "i18n_close": re.escape(")"),
  530. }
  531. constant_string = constant_string.replace("\n", "")
  532. filter_raw_string = r"""
  533. ^(?P<constant>%(constant)s)|
  534. ^(?P<var>[%(var_chars)s]+|%(num)s)|
  535. (?:\s*%(filter_sep)s\s*
  536. (?P<filter_name>\w+)
  537. (?:%(arg_sep)s
  538. (?:
  539. (?P<constant_arg>%(constant)s)|
  540. (?P<var_arg>[%(var_chars)s]+|%(num)s)
  541. )
  542. )?
  543. )""" % {
  544. "constant": constant_string,
  545. "num": r"[-+\.]?\d[\d\.e]*",
  546. "var_chars": r"\w\.",
  547. "filter_sep": re.escape(FILTER_SEPARATOR),
  548. "arg_sep": re.escape(FILTER_ARGUMENT_SEPARATOR),
  549. }
  550. filter_re = _lazy_re_compile(filter_raw_string, re.VERBOSE)
  551. class FilterExpression:
  552. """
  553. Parse a variable token and its optional filters (all as a single string),
  554. and return a list of tuples of the filter name and arguments.
  555. Sample::
  556. >>> token = 'variable|default:"Default value"|date:"Y-m-d"'
  557. >>> p = Parser('')
  558. >>> fe = FilterExpression(token, p)
  559. >>> len(fe.filters)
  560. 2
  561. >>> fe.var
  562. <Variable: 'variable'>
  563. """
  564. __slots__ = ("token", "filters", "var", "is_var")
  565. def __init__(self, token, parser):
  566. self.token = token
  567. matches = filter_re.finditer(token)
  568. var_obj = None
  569. filters = []
  570. upto = 0
  571. for match in matches:
  572. start = match.start()
  573. if upto != start:
  574. raise TemplateSyntaxError(
  575. "Could not parse some characters: "
  576. "%s|%s|%s" % (token[:upto], token[upto:start], token[start:])
  577. )
  578. if var_obj is None:
  579. var, constant = match["var"], match["constant"]
  580. if constant:
  581. try:
  582. var_obj = Variable(constant).resolve({})
  583. except VariableDoesNotExist:
  584. var_obj = None
  585. elif var is None:
  586. raise TemplateSyntaxError(
  587. "Could not find variable at start of %s." % token
  588. )
  589. else:
  590. var_obj = Variable(var)
  591. else:
  592. filter_name = match["filter_name"]
  593. args = []
  594. constant_arg, var_arg = match["constant_arg"], match["var_arg"]
  595. if constant_arg:
  596. args.append((False, Variable(constant_arg).resolve({})))
  597. elif var_arg:
  598. args.append((True, Variable(var_arg)))
  599. filter_func = parser.find_filter(filter_name)
  600. self.args_check(filter_name, filter_func, args)
  601. filters.append((filter_func, args))
  602. upto = match.end()
  603. if upto != len(token):
  604. raise TemplateSyntaxError(
  605. "Could not parse the remainder: '%s' "
  606. "from '%s'" % (token[upto:], token)
  607. )
  608. self.filters = filters
  609. self.var = var_obj
  610. self.is_var = isinstance(var_obj, Variable)
  611. def resolve(self, context, ignore_failures=False):
  612. if self.is_var:
  613. try:
  614. obj = self.var.resolve(context)
  615. except VariableDoesNotExist:
  616. if ignore_failures:
  617. obj = None
  618. else:
  619. string_if_invalid = context.template.engine.string_if_invalid
  620. if string_if_invalid:
  621. if "%s" in string_if_invalid:
  622. return string_if_invalid % self.var
  623. else:
  624. return string_if_invalid
  625. else:
  626. obj = string_if_invalid
  627. else:
  628. obj = self.var
  629. for func, args in self.filters:
  630. arg_vals = []
  631. for lookup, arg in args:
  632. if not lookup:
  633. arg_vals.append(mark_safe(arg))
  634. else:
  635. arg_vals.append(arg.resolve(context))
  636. if getattr(func, "expects_localtime", False):
  637. obj = template_localtime(obj, context.use_tz)
  638. if getattr(func, "needs_autoescape", False):
  639. new_obj = func(obj, autoescape=context.autoescape, *arg_vals)
  640. else:
  641. new_obj = func(obj, *arg_vals)
  642. if getattr(func, "is_safe", False) and isinstance(obj, SafeData):
  643. obj = mark_safe(new_obj)
  644. else:
  645. obj = new_obj
  646. return obj
  647. def args_check(name, func, provided):
  648. provided = list(provided)
  649. # First argument, filter input, is implied.
  650. plen = len(provided) + 1
  651. # Check to see if a decorator is providing the real function.
  652. func = inspect.unwrap(func)
  653. args, _, _, defaults, _, _, _ = inspect.getfullargspec(func)
  654. alen = len(args)
  655. dlen = len(defaults or [])
  656. # Not enough OR Too many
  657. if plen < (alen - dlen) or plen > alen:
  658. raise TemplateSyntaxError(
  659. "%s requires %d arguments, %d provided" % (name, alen - dlen, plen)
  660. )
  661. return True
  662. args_check = staticmethod(args_check)
  663. def __str__(self):
  664. return self.token
  665. def __repr__(self):
  666. return "<%s %r>" % (self.__class__.__qualname__, self.token)
  667. class Variable:
  668. """
  669. A template variable, resolvable against a given context. The variable may
  670. be a hard-coded string (if it begins and ends with single or double quote
  671. marks)::
  672. >>> c = {'article': {'section':'News'}}
  673. >>> Variable('article.section').resolve(c)
  674. 'News'
  675. >>> Variable('article').resolve(c)
  676. {'section': 'News'}
  677. >>> class AClass: pass
  678. >>> c = AClass()
  679. >>> c.article = AClass()
  680. >>> c.article.section = 'News'
  681. (The example assumes VARIABLE_ATTRIBUTE_SEPARATOR is '.')
  682. """
  683. __slots__ = ("var", "literal", "lookups", "translate", "message_context")
  684. def __init__(self, var):
  685. self.var = var
  686. self.literal = None
  687. self.lookups = None
  688. self.translate = False
  689. self.message_context = None
  690. if not isinstance(var, str):
  691. raise TypeError("Variable must be a string or number, got %s" % type(var))
  692. try:
  693. # First try to treat this variable as a number.
  694. #
  695. # Note that this could cause an OverflowError here that we're not
  696. # catching. Since this should only happen at compile time, that's
  697. # probably OK.
  698. # Try to interpret values containing a period or an 'e'/'E'
  699. # (possibly scientific notation) as a float; otherwise, try int.
  700. if "." in var or "e" in var.lower():
  701. self.literal = float(var)
  702. # "2." is invalid
  703. if var[-1] == ".":
  704. raise ValueError
  705. else:
  706. self.literal = int(var)
  707. except ValueError:
  708. # A ValueError means that the variable isn't a number.
  709. if var[0:2] == "_(" and var[-1] == ")":
  710. # The result of the lookup should be translated at rendering
  711. # time.
  712. self.translate = True
  713. var = var[2:-1]
  714. # If it's wrapped with quotes (single or double), then
  715. # we're also dealing with a literal.
  716. try:
  717. self.literal = mark_safe(unescape_string_literal(var))
  718. except ValueError:
  719. # Otherwise we'll set self.lookups so that resolve() knows we're
  720. # dealing with a bonafide variable
  721. if VARIABLE_ATTRIBUTE_SEPARATOR + "_" in var or var[0] == "_":
  722. raise TemplateSyntaxError(
  723. "Variables and attributes may "
  724. "not begin with underscores: '%s'" % var
  725. )
  726. self.lookups = tuple(var.split(VARIABLE_ATTRIBUTE_SEPARATOR))
  727. def resolve(self, context):
  728. """Resolve this variable against a given context."""
  729. if self.lookups is not None:
  730. # We're dealing with a variable that needs to be resolved
  731. value = self._resolve_lookup(context)
  732. else:
  733. # We're dealing with a literal, so it's already been "resolved"
  734. value = self.literal
  735. if self.translate:
  736. is_safe = isinstance(value, SafeData)
  737. msgid = value.replace("%", "%%")
  738. msgid = mark_safe(msgid) if is_safe else msgid
  739. if self.message_context:
  740. return pgettext_lazy(self.message_context, msgid)
  741. else:
  742. return gettext_lazy(msgid)
  743. return value
  744. def __repr__(self):
  745. return "<%s: %r>" % (self.__class__.__name__, self.var)
  746. def __str__(self):
  747. return self.var
  748. def _resolve_lookup(self, context):
  749. """
  750. Perform resolution of a real variable (i.e. not a literal) against the
  751. given context.
  752. As indicated by the method's name, this method is an implementation
  753. detail and shouldn't be called by external code. Use Variable.resolve()
  754. instead.
  755. """
  756. current = context
  757. try: # catch-all for silent variable failures
  758. for bit in self.lookups:
  759. try: # dictionary lookup
  760. current = current[bit]
  761. # ValueError/IndexError are for numpy.array lookup on
  762. # numpy < 1.9 and 1.9+ respectively
  763. except (TypeError, AttributeError, KeyError, ValueError, IndexError):
  764. try: # attribute lookup
  765. # Don't return class attributes if the class is the context:
  766. if isinstance(current, BaseContext) and getattr(
  767. type(current), bit
  768. ):
  769. raise AttributeError
  770. current = getattr(current, bit)
  771. except (TypeError, AttributeError):
  772. # Reraise if the exception was raised by a @property
  773. if not isinstance(current, BaseContext) and bit in dir(current):
  774. raise
  775. try: # list-index lookup
  776. current = current[int(bit)]
  777. except (
  778. IndexError, # list index out of range
  779. ValueError, # invalid literal for int()
  780. KeyError, # current is a dict without `int(bit)` key
  781. TypeError,
  782. ): # unsubscriptable object
  783. raise VariableDoesNotExist(
  784. "Failed lookup for key [%s] in %r",
  785. (bit, current),
  786. ) # missing attribute
  787. if callable(current):
  788. if getattr(current, "do_not_call_in_templates", False):
  789. pass
  790. elif getattr(current, "alters_data", False):
  791. current = context.template.engine.string_if_invalid
  792. else:
  793. try: # method call (assuming no args required)
  794. current = current()
  795. except TypeError:
  796. try:
  797. signature = inspect.signature(current)
  798. except ValueError: # No signature found.
  799. current = context.template.engine.string_if_invalid
  800. else:
  801. try:
  802. signature.bind()
  803. except TypeError: # Arguments *were* required.
  804. # Invalid method call.
  805. current = context.template.engine.string_if_invalid
  806. else:
  807. raise
  808. except Exception as e:
  809. template_name = getattr(context, "template_name", None) or "unknown"
  810. logger.debug(
  811. "Exception while resolving variable '%s' in template '%s'.",
  812. bit,
  813. template_name,
  814. exc_info=True,
  815. )
  816. if getattr(e, "silent_variable_failure", False):
  817. current = context.template.engine.string_if_invalid
  818. else:
  819. raise
  820. return current
  821. class Node:
  822. # Set this to True for nodes that must be first in the template (although
  823. # they can be preceded by text nodes.
  824. must_be_first = False
  825. child_nodelists = ("nodelist",)
  826. token = None
  827. def render(self, context):
  828. """
  829. Return the node rendered as a string.
  830. """
  831. pass
  832. def render_annotated(self, context):
  833. """
  834. Render the node. If debug is True and an exception occurs during
  835. rendering, the exception is annotated with contextual line information
  836. where it occurred in the template. For internal usage this method is
  837. preferred over using the render method directly.
  838. """
  839. try:
  840. return self.render(context)
  841. except Exception as e:
  842. if context.template.engine.debug:
  843. # Store the actual node that caused the exception.
  844. if not hasattr(e, "_culprit_node"):
  845. e._culprit_node = self
  846. if (
  847. not hasattr(e, "template_debug")
  848. and context.render_context.template.origin == e._culprit_node.origin
  849. ):
  850. e.template_debug = (
  851. context.render_context.template.get_exception_info(
  852. e,
  853. e._culprit_node.token,
  854. )
  855. )
  856. raise
  857. def get_nodes_by_type(self, nodetype):
  858. """
  859. Return a list of all nodes (within this node and its nodelist)
  860. of the given type
  861. """
  862. nodes = []
  863. if isinstance(self, nodetype):
  864. nodes.append(self)
  865. for attr in self.child_nodelists:
  866. nodelist = getattr(self, attr, None)
  867. if nodelist:
  868. nodes.extend(nodelist.get_nodes_by_type(nodetype))
  869. return nodes
  870. class NodeList(list):
  871. # Set to True the first time a non-TextNode is inserted by
  872. # extend_nodelist().
  873. contains_nontext = False
  874. def render(self, context):
  875. return SafeString("".join([node.render_annotated(context) for node in self]))
  876. def get_nodes_by_type(self, nodetype):
  877. "Return a list of all nodes of the given type"
  878. nodes = []
  879. for node in self:
  880. nodes.extend(node.get_nodes_by_type(nodetype))
  881. return nodes
  882. class TextNode(Node):
  883. child_nodelists = ()
  884. def __init__(self, s):
  885. self.s = s
  886. def __repr__(self):
  887. return "<%s: %r>" % (self.__class__.__name__, self.s[:25])
  888. def render(self, context):
  889. return self.s
  890. def render_annotated(self, context):
  891. """
  892. Return the given value.
  893. The default implementation of this method handles exceptions raised
  894. during rendering, which is not necessary for text nodes.
  895. """
  896. return self.s
  897. def render_value_in_context(value, context):
  898. """
  899. Convert any value to a string to become part of a rendered template. This
  900. means escaping, if required, and conversion to a string. If value is a
  901. string, it's expected to already be translated.
  902. """
  903. value = template_localtime(value, use_tz=context.use_tz)
  904. value = localize(value, use_l10n=context.use_l10n)
  905. if context.autoescape:
  906. if not issubclass(type(value), str):
  907. value = str(value)
  908. return conditional_escape(value)
  909. else:
  910. return str(value)
  911. class VariableNode(Node):
  912. child_nodelists = ()
  913. def __init__(self, filter_expression):
  914. self.filter_expression = filter_expression
  915. def __repr__(self):
  916. return "<Variable Node: %s>" % self.filter_expression
  917. def render(self, context):
  918. try:
  919. output = self.filter_expression.resolve(context)
  920. except UnicodeDecodeError:
  921. # Unicode conversion can fail sometimes for reasons out of our
  922. # control (e.g. exception rendering). In that case, we fail
  923. # quietly.
  924. return ""
  925. return render_value_in_context(output, context)
  926. # Regex for token keyword arguments
  927. kwarg_re = _lazy_re_compile(r"(?:(\w+)=)?(.+)")
  928. def token_kwargs(bits, parser, support_legacy=False):
  929. """
  930. Parse token keyword arguments and return a dictionary of the arguments
  931. retrieved from the ``bits`` token list.
  932. `bits` is a list containing the remainder of the token (split by spaces)
  933. that is to be checked for arguments. Valid arguments are removed from this
  934. list.
  935. `support_legacy` - if True, the legacy format ``1 as foo`` is accepted.
  936. Otherwise, only the standard ``foo=1`` format is allowed.
  937. There is no requirement for all remaining token ``bits`` to be keyword
  938. arguments, so return the dictionary as soon as an invalid argument format
  939. is reached.
  940. """
  941. if not bits:
  942. return {}
  943. match = kwarg_re.match(bits[0])
  944. kwarg_format = match and match[1]
  945. if not kwarg_format:
  946. if not support_legacy:
  947. return {}
  948. if len(bits) < 3 or bits[1] != "as":
  949. return {}
  950. kwargs = {}
  951. while bits:
  952. if kwarg_format:
  953. match = kwarg_re.match(bits[0])
  954. if not match or not match[1]:
  955. return kwargs
  956. key, value = match.groups()
  957. del bits[:1]
  958. else:
  959. if len(bits) < 3 or bits[1] != "as":
  960. return kwargs
  961. key, value = bits[2], bits[0]
  962. del bits[:3]
  963. kwargs[key] = parser.compile_filter(value)
  964. if bits and not kwarg_format:
  965. if bits[0] != "and":
  966. return kwargs
  967. del bits[:1]
  968. return kwargs