base.py 37 KB

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