base.py 37 KB

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