PageRenderTime 58ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/django/template/base.py

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