2014-11-11 04:40:26 +08:00
|
|
|
"""
|
|
|
|
This is the Django template system.
|
|
|
|
|
|
|
|
How it works:
|
|
|
|
|
2018-05-10 23:51:51 +08:00
|
|
|
The Lexer.tokenize() method converts a template string (i.e., a string
|
|
|
|
containing markup with custom template tags) to tokens, which can be either
|
|
|
|
plain text (TokenType.TEXT), variables (TokenType.VAR), or block statements
|
|
|
|
(TokenType.BLOCK).
|
2014-11-11 04:40:26 +08:00
|
|
|
|
|
|
|
The Parser() class takes a list of tokens in its constructor, and its parse()
|
|
|
|
method returns a compiled template -- which is, under the hood, a list of
|
|
|
|
Node objects.
|
|
|
|
|
|
|
|
Each Node is responsible for creating some sort of output -- e.g. simple text
|
|
|
|
(TextNode), variable values in a given context (VariableNode), results of basic
|
|
|
|
logic (IfNode), results of looping (ForNode), or anything else. The core Node
|
|
|
|
types are TextNode, VariableNode, IfNode and ForNode, but plugin modules can
|
|
|
|
define their own custom node types.
|
|
|
|
|
|
|
|
Each Node has a render() method, which takes a Context and returns a string of
|
|
|
|
the rendered node. For example, the render() method of a Variable Node returns
|
|
|
|
the variable's value as a string. The render() method of a ForNode returns the
|
|
|
|
rendered output of whatever was inside the loop, recursively.
|
|
|
|
|
|
|
|
The Template class is a convenient wrapper that takes care of template
|
|
|
|
compilation and rendering.
|
|
|
|
|
|
|
|
Usage:
|
|
|
|
|
|
|
|
The only thing you should ever use directly in this file is the Template class.
|
|
|
|
Create a compiled template object with a template_string, then call render()
|
|
|
|
with a context. In the compilation stage, the TemplateSyntaxError exception
|
|
|
|
will be raised if the template doesn't have proper syntax.
|
|
|
|
|
|
|
|
Sample code:
|
|
|
|
|
|
|
|
>>> from django import template
|
2015-07-06 21:17:28 +08:00
|
|
|
>>> s = '<html>{% if test %}<h1>{{ varvalue }}</h1>{% endif %}</html>'
|
2014-11-11 04:40:26 +08:00
|
|
|
>>> t = template.Template(s)
|
|
|
|
|
|
|
|
(t is now a compiled template, and its render() method can be called multiple
|
|
|
|
times with multiple contexts)
|
|
|
|
|
|
|
|
>>> c = template.Context({'test':True, 'varvalue': 'Hello'})
|
|
|
|
>>> t.render(c)
|
2015-07-06 21:17:28 +08:00
|
|
|
'<html><h1>Hello</h1></html>'
|
2014-11-11 04:40:26 +08:00
|
|
|
>>> c = template.Context({'test':False, 'varvalue': 'Hello'})
|
|
|
|
>>> t.render(c)
|
2015-07-06 21:17:28 +08:00
|
|
|
'<html></html>'
|
2014-11-11 04:40:26 +08:00
|
|
|
"""
|
|
|
|
|
2019-12-10 00:33:51 +08:00
|
|
|
import inspect
|
2014-04-15 05:18:03 +08:00
|
|
|
import logging
|
2010-11-27 13:47:30 +08:00
|
|
|
import re
|
2018-05-10 23:51:51 +08:00
|
|
|
from enum import Enum
|
2010-11-27 13:47:30 +08:00
|
|
|
|
2019-07-18 14:13:01 +08:00
|
|
|
from django.template.context import BaseContext
|
2010-11-27 13:47:30 +08:00
|
|
|
from django.utils.formats import localize
|
2015-03-06 23:53:25 +08:00
|
|
|
from django.utils.html import conditional_escape, escape
|
2019-10-26 22:42:32 +08:00
|
|
|
from django.utils.regex_helper import _lazy_re_compile
|
2021-06-07 19:56:50 +08:00
|
|
|
from django.utils.safestring import SafeData, SafeString, mark_safe
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.utils.text import (
|
|
|
|
get_text_list, smart_split, unescape_string_literal,
|
|
|
|
)
|
2012-04-29 21:37:23 +08:00
|
|
|
from django.utils.timezone import template_localtime
|
2017-01-27 03:58:33 +08:00
|
|
|
from django.utils.translation import gettext_lazy, pgettext_lazy
|
2010-11-27 13:47:30 +08:00
|
|
|
|
2015-04-25 03:35:30 +08:00
|
|
|
from .exceptions import TemplateSyntaxError
|
|
|
|
|
2010-11-27 13:47:30 +08:00
|
|
|
# template syntax constants
|
|
|
|
FILTER_SEPARATOR = '|'
|
|
|
|
FILTER_ARGUMENT_SEPARATOR = ':'
|
|
|
|
VARIABLE_ATTRIBUTE_SEPARATOR = '.'
|
|
|
|
BLOCK_TAG_START = '{%'
|
|
|
|
BLOCK_TAG_END = '%}'
|
|
|
|
VARIABLE_TAG_START = '{{'
|
|
|
|
VARIABLE_TAG_END = '}}'
|
|
|
|
COMMENT_TAG_START = '{#'
|
|
|
|
COMMENT_TAG_END = '#}'
|
|
|
|
SINGLE_BRACE_START = '{'
|
|
|
|
SINGLE_BRACE_END = '}'
|
|
|
|
|
|
|
|
# what to report as the origin for templates that come from non-loader sources
|
|
|
|
# (e.g. strings)
|
|
|
|
UNKNOWN_SOURCE = '<unknown source>'
|
|
|
|
|
2021-08-06 18:45:17 +08:00
|
|
|
# Match BLOCK_TAG_*, VARIABLE_TAG_*, and COMMENT_TAG_* tags and capture the
|
|
|
|
# entire tag, including start/end delimiters. Using re.compile() is faster
|
|
|
|
# than instantiating SimpleLazyObject with _lazy_re_compile().
|
|
|
|
tag_re = re.compile(r'({%.*?%}|{{.*?}}|{#.*?#})')
|
2010-11-27 13:47:30 +08:00
|
|
|
|
2014-04-15 05:18:03 +08:00
|
|
|
logger = logging.getLogger('django.template')
|
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2018-05-10 23:51:51 +08:00
|
|
|
class TokenType(Enum):
|
|
|
|
TEXT = 0
|
|
|
|
VAR = 1
|
|
|
|
BLOCK = 2
|
|
|
|
COMMENT = 3
|
|
|
|
|
|
|
|
|
2010-11-27 13:47:30 +08:00
|
|
|
class VariableDoesNotExist(Exception):
|
|
|
|
|
|
|
|
def __init__(self, msg, params=()):
|
|
|
|
self.msg = msg
|
|
|
|
self.params = params
|
|
|
|
|
2012-08-12 18:32:08 +08:00
|
|
|
def __str__(self):
|
2017-01-27 04:10:15 +08:00
|
|
|
return self.msg % self.params
|
2010-11-27 13:47:30 +08:00
|
|
|
|
2013-11-03 08:37:15 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class Origin:
|
2015-03-04 05:48:26 +08:00
|
|
|
def __init__(self, name, template_name=None, loader=None):
|
2010-11-27 13:47:30 +08:00
|
|
|
self.name = name
|
2015-03-04 05:48:26 +08:00
|
|
|
self.template_name = template_name
|
|
|
|
self.loader = loader
|
2010-11-27 13:47:30 +08:00
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return self.name
|
|
|
|
|
2021-03-13 06:37:47 +08:00
|
|
|
def __repr__(self):
|
|
|
|
return '<%s name=%r>' % (self.__class__.__qualname__, self.name)
|
|
|
|
|
2015-03-04 05:48:26 +08:00
|
|
|
def __eq__(self, other):
|
|
|
|
return (
|
2017-09-28 17:39:12 +08:00
|
|
|
isinstance(other, Origin) and
|
2015-03-04 05:48:26 +08:00
|
|
|
self.name == other.name and
|
|
|
|
self.loader == other.loader
|
|
|
|
)
|
2010-11-27 13:47:30 +08:00
|
|
|
|
2015-03-04 05:48:26 +08:00
|
|
|
@property
|
|
|
|
def loader_name(self):
|
|
|
|
if self.loader:
|
|
|
|
return '%s.%s' % (
|
|
|
|
self.loader.__module__, self.loader.__class__.__name__,
|
|
|
|
)
|
2010-11-27 13:47:30 +08:00
|
|
|
|
2013-11-03 08:37:15 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class Template:
|
2014-11-14 22:48:27 +08:00
|
|
|
def __init__(self, template_string, origin=None, name=None, engine=None):
|
2014-11-29 06:04:19 +08:00
|
|
|
# If Template is instantiated directly rather than from an Engine and
|
|
|
|
# exactly one Django template engine is configured, use that engine.
|
|
|
|
# This is required to preserve backwards-compatibility for direct use
|
|
|
|
# e.g. Template('...').render(Context({...}))
|
2014-11-14 22:48:27 +08:00
|
|
|
if engine is None:
|
|
|
|
from .engine import Engine
|
|
|
|
engine = Engine.get_default()
|
2015-03-06 23:53:25 +08:00
|
|
|
if origin is None:
|
2015-03-04 05:48:26 +08:00
|
|
|
origin = Origin(UNKNOWN_SOURCE)
|
2010-11-27 13:47:30 +08:00
|
|
|
self.name = name
|
2013-08-31 03:08:40 +08:00
|
|
|
self.origin = origin
|
2014-11-14 22:48:27 +08:00
|
|
|
self.engine = engine
|
2018-07-31 21:57:11 +08:00
|
|
|
self.source = str(template_string) # May be lazy.
|
2015-03-06 23:53:25 +08:00
|
|
|
self.nodelist = self.compile_nodelist()
|
2010-11-27 13:47:30 +08:00
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
for node in self.nodelist:
|
2017-02-24 09:06:01 +08:00
|
|
|
yield from node
|
2010-11-27 13:47:30 +08:00
|
|
|
|
2021-03-13 06:37:47 +08:00
|
|
|
def __repr__(self):
|
|
|
|
return '<%s template_string="%s...">' % (
|
|
|
|
self.__class__.__qualname__,
|
|
|
|
self.source[:20].replace('\n', ''),
|
|
|
|
)
|
|
|
|
|
2010-11-27 13:47:30 +08:00
|
|
|
def _render(self, context):
|
|
|
|
return self.nodelist.render(context)
|
|
|
|
|
|
|
|
def render(self, context):
|
|
|
|
"Display stage -- can be called many times"
|
2016-12-14 10:35:21 +08:00
|
|
|
with context.render_context.push_state(self):
|
2015-02-20 06:20:27 +08:00
|
|
|
if context.template is None:
|
|
|
|
with context.bind_template(self):
|
2014-04-15 05:18:03 +08:00
|
|
|
context.template_name = self.name
|
2015-02-20 06:20:27 +08:00
|
|
|
return self._render(context)
|
|
|
|
else:
|
|
|
|
return self._render(context)
|
2010-11-27 13:47:30 +08:00
|
|
|
|
2015-03-06 23:53:25 +08:00
|
|
|
def compile_nodelist(self):
|
|
|
|
"""
|
|
|
|
Parse and compile the template source into a nodelist. If debug
|
|
|
|
is True and an exception occurs during parsing, the exception is
|
2019-09-11 18:55:17 +08:00
|
|
|
annotated with contextual line information where it occurred in the
|
2015-03-06 23:53:25 +08:00
|
|
|
template source.
|
|
|
|
"""
|
|
|
|
if self.engine.debug:
|
|
|
|
lexer = DebugLexer(self.source)
|
|
|
|
else:
|
|
|
|
lexer = Lexer(self.source)
|
|
|
|
|
|
|
|
tokens = lexer.tokenize()
|
2015-05-09 04:10:36 +08:00
|
|
|
parser = Parser(
|
|
|
|
tokens, self.engine.template_libraries, self.engine.template_builtins,
|
2016-01-15 10:36:05 +08:00
|
|
|
self.origin,
|
2015-05-09 04:10:36 +08:00
|
|
|
)
|
2015-03-06 23:53:25 +08:00
|
|
|
|
|
|
|
try:
|
|
|
|
return parser.parse()
|
|
|
|
except Exception as e:
|
|
|
|
if self.engine.debug:
|
|
|
|
e.template_debug = self.get_exception_info(e, e.token)
|
|
|
|
raise
|
|
|
|
|
|
|
|
def get_exception_info(self, exception, token):
|
|
|
|
"""
|
|
|
|
Return a dictionary containing contextual line information of where
|
|
|
|
the exception occurred in the template. The following information is
|
|
|
|
provided:
|
|
|
|
|
|
|
|
message
|
|
|
|
The message of the exception raised.
|
|
|
|
|
|
|
|
source_lines
|
|
|
|
The lines before, after, and including the line the exception
|
|
|
|
occurred on.
|
|
|
|
|
|
|
|
line
|
|
|
|
The line number the exception occurred on.
|
|
|
|
|
|
|
|
before, during, after
|
|
|
|
The line the exception occurred on split into three parts:
|
|
|
|
1. The content before the token that raised the error.
|
|
|
|
2. The token that raised the error.
|
|
|
|
3. The content after the token that raised the error.
|
|
|
|
|
|
|
|
total
|
|
|
|
The number of lines in source_lines.
|
|
|
|
|
|
|
|
top
|
|
|
|
The line number where source_lines starts.
|
|
|
|
|
|
|
|
bottom
|
|
|
|
The line number where source_lines ends.
|
|
|
|
|
|
|
|
start
|
|
|
|
The start position of the token in the template source.
|
|
|
|
|
|
|
|
end
|
|
|
|
The end position of the token in the template source.
|
|
|
|
"""
|
|
|
|
start, end = token.position
|
|
|
|
context_lines = 10
|
|
|
|
line = 0
|
|
|
|
upto = 0
|
|
|
|
source_lines = []
|
|
|
|
before = during = after = ""
|
|
|
|
for num, next in enumerate(linebreak_iter(self.source)):
|
|
|
|
if start >= upto and end <= next:
|
|
|
|
line = num
|
|
|
|
before = escape(self.source[upto:start])
|
|
|
|
during = escape(self.source[start:end])
|
|
|
|
after = escape(self.source[end:next])
|
|
|
|
source_lines.append((num, escape(self.source[upto:next])))
|
|
|
|
upto = next
|
|
|
|
total = len(source_lines)
|
|
|
|
|
|
|
|
top = max(1, line - context_lines)
|
|
|
|
bottom = min(total, line + 1 + context_lines)
|
|
|
|
|
|
|
|
# In some rare cases exc_value.args can be empty or an invalid
|
2017-01-21 05:04:05 +08:00
|
|
|
# string.
|
2015-03-06 23:53:25 +08:00
|
|
|
try:
|
2017-02-07 16:17:38 +08:00
|
|
|
message = str(exception.args[0])
|
2015-03-06 23:53:25 +08:00
|
|
|
except (IndexError, UnicodeDecodeError):
|
|
|
|
message = '(Could not get exception message)'
|
|
|
|
|
|
|
|
return {
|
|
|
|
'message': message,
|
|
|
|
'source_lines': source_lines[top:bottom],
|
|
|
|
'before': before,
|
|
|
|
'during': during,
|
|
|
|
'after': after,
|
|
|
|
'top': top,
|
|
|
|
'bottom': bottom,
|
|
|
|
'total': total,
|
|
|
|
'line': line,
|
|
|
|
'name': self.origin.name,
|
|
|
|
'start': start,
|
|
|
|
'end': end,
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
def linebreak_iter(template_source):
|
|
|
|
yield 0
|
|
|
|
p = template_source.find('\n')
|
|
|
|
while p >= 0:
|
|
|
|
yield p + 1
|
|
|
|
p = template_source.find('\n', p + 1)
|
|
|
|
yield len(template_source) + 1
|
|
|
|
|
2013-11-03 08:37:15 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class Token:
|
2015-03-06 23:53:25 +08:00
|
|
|
def __init__(self, token_type, contents, position=None, lineno=None):
|
|
|
|
"""
|
|
|
|
A token representing a string from the template.
|
|
|
|
|
|
|
|
token_type
|
2018-05-10 23:51:51 +08:00
|
|
|
A TokenType, either .TEXT, .VAR, .BLOCK, or .COMMENT.
|
2015-03-06 23:53:25 +08:00
|
|
|
|
|
|
|
contents
|
|
|
|
The token source string.
|
|
|
|
|
|
|
|
position
|
|
|
|
An optional tuple containing the start and end index of the token
|
|
|
|
in the template source. This is used for traceback information
|
|
|
|
when debug is on.
|
|
|
|
|
|
|
|
lineno
|
|
|
|
The line number the token appears on in the template source.
|
|
|
|
This is used for traceback information and gettext files.
|
|
|
|
"""
|
2010-11-27 13:47:30 +08:00
|
|
|
self.token_type, self.contents = token_type, contents
|
2015-03-06 23:53:25 +08:00
|
|
|
self.lineno = lineno
|
|
|
|
self.position = position
|
2010-11-27 13:47:30 +08:00
|
|
|
|
2021-01-30 03:21:26 +08:00
|
|
|
def __repr__(self):
|
2018-05-10 23:51:51 +08:00
|
|
|
token_name = self.token_type.name.capitalize()
|
2011-09-27 20:15:15 +08:00
|
|
|
return ('<%s token: "%s...">' %
|
|
|
|
(token_name, self.contents[:20].replace('\n', '')))
|
2010-11-27 13:47:30 +08:00
|
|
|
|
|
|
|
def split_contents(self):
|
|
|
|
split = []
|
2017-08-24 04:48:29 +08:00
|
|
|
bits = smart_split(self.contents)
|
2010-11-27 13:47:30 +08:00
|
|
|
for bit in bits:
|
|
|
|
# Handle translation-marked template pieces
|
2015-03-14 03:08:04 +08:00
|
|
|
if bit.startswith(('_("', "_('")):
|
2015-12-03 07:55:50 +08:00
|
|
|
sentinel = bit[2] + ')'
|
2010-11-27 13:47:30 +08:00
|
|
|
trans_bit = [bit]
|
2015-12-03 07:55:50 +08:00
|
|
|
while not bit.endswith(sentinel):
|
2012-05-11 02:14:04 +08:00
|
|
|
bit = next(bits)
|
2010-11-27 13:47:30 +08:00
|
|
|
trans_bit.append(bit)
|
|
|
|
bit = ' '.join(trans_bit)
|
|
|
|
split.append(bit)
|
|
|
|
return split
|
|
|
|
|
2013-11-03 08:37:15 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class Lexer:
|
2015-03-06 23:53:25 +08:00
|
|
|
def __init__(self, template_string):
|
2010-11-27 13:47:30 +08:00
|
|
|
self.template_string = template_string
|
2012-06-07 15:59:14 +08:00
|
|
|
self.verbatim = False
|
2010-11-27 13:47:30 +08:00
|
|
|
|
2021-01-30 03:21:26 +08:00
|
|
|
def __repr__(self):
|
|
|
|
return '<%s template_string="%s...", verbatim=%s>' % (
|
|
|
|
self.__class__.__qualname__,
|
|
|
|
self.template_string[:20].replace('\n', ''),
|
|
|
|
self.verbatim,
|
|
|
|
)
|
|
|
|
|
2010-11-27 13:47:30 +08:00
|
|
|
def tokenize(self):
|
2011-09-27 20:15:15 +08:00
|
|
|
"""
|
|
|
|
Return a list of tokens from a given template_string.
|
|
|
|
"""
|
2010-11-27 13:47:30 +08:00
|
|
|
in_tag = False
|
2015-03-06 23:53:25 +08:00
|
|
|
lineno = 1
|
2010-11-27 13:47:30 +08:00
|
|
|
result = []
|
2021-08-09 11:49:09 +08:00
|
|
|
for token_string in tag_re.split(self.template_string):
|
|
|
|
if token_string:
|
|
|
|
result.append(self.create_token(token_string, None, lineno, in_tag))
|
|
|
|
lineno += token_string.count('\n')
|
2010-11-27 13:47:30 +08:00
|
|
|
in_tag = not in_tag
|
|
|
|
return result
|
|
|
|
|
2015-03-06 23:53:25 +08:00
|
|
|
def create_token(self, token_string, position, lineno, in_tag):
|
2010-11-27 13:47:30 +08:00
|
|
|
"""
|
|
|
|
Convert the given token string into a new Token object and return it.
|
|
|
|
If in_tag is True, we are processing something that matched a tag,
|
|
|
|
otherwise it should be treated as a literal string.
|
|
|
|
"""
|
2021-08-03 23:21:22 +08:00
|
|
|
if in_tag:
|
|
|
|
# The [0:2] and [2:-2] ranges below strip off *_TAG_START and
|
|
|
|
# *_TAG_END. The 2's are hard-coded for performance. Using
|
|
|
|
# len(BLOCK_TAG_START) would permit BLOCK_TAG_START to be
|
|
|
|
# different, but it's not likely that the TAG_START values will
|
|
|
|
# change anytime soon.
|
|
|
|
token_start = token_string[0:2]
|
|
|
|
if token_start == BLOCK_TAG_START:
|
|
|
|
content = token_string[2:-2].strip()
|
|
|
|
if self.verbatim:
|
|
|
|
# Then a verbatim block is being processed.
|
|
|
|
if content != self.verbatim:
|
|
|
|
return Token(TokenType.TEXT, token_string, position, lineno)
|
|
|
|
# Otherwise, the current verbatim block is ending.
|
|
|
|
self.verbatim = False
|
|
|
|
elif content[:9] in ('verbatim', 'verbatim '):
|
|
|
|
# Then a verbatim block is starting.
|
|
|
|
self.verbatim = 'end%s' % content
|
|
|
|
return Token(TokenType.BLOCK, content, position, lineno)
|
|
|
|
if not self.verbatim:
|
|
|
|
content = token_string[2:-2].strip()
|
|
|
|
if token_start == VARIABLE_TAG_START:
|
|
|
|
return Token(TokenType.VAR, content, position, lineno)
|
|
|
|
# BLOCK_TAG_START was handled above.
|
|
|
|
assert token_start == COMMENT_TAG_START
|
|
|
|
return Token(TokenType.COMMENT, content, position, lineno)
|
|
|
|
return Token(TokenType.TEXT, token_string, position, lineno)
|
2010-11-27 13:47:30 +08:00
|
|
|
|
2013-11-03 08:37:15 +08:00
|
|
|
|
2015-03-06 23:53:25 +08:00
|
|
|
class DebugLexer(Lexer):
|
2021-08-08 13:12:27 +08:00
|
|
|
def _tag_re_split_positions(self):
|
|
|
|
last = 0
|
|
|
|
for match in tag_re.finditer(self.template_string):
|
|
|
|
start, end = match.span()
|
|
|
|
yield last, start
|
|
|
|
yield start, end
|
|
|
|
last = end
|
|
|
|
yield last, len(self.template_string)
|
|
|
|
|
|
|
|
# This parallels the use of tag_re.split() in Lexer.tokenize().
|
|
|
|
def _tag_re_split(self):
|
|
|
|
for position in self._tag_re_split_positions():
|
|
|
|
yield self.template_string[slice(*position)], position
|
|
|
|
|
2015-03-06 23:53:25 +08:00
|
|
|
def tokenize(self):
|
|
|
|
"""
|
|
|
|
Split a template string into tokens and annotates each token with its
|
|
|
|
start and end position in the source. This is slower than the default
|
2017-01-25 04:36:36 +08:00
|
|
|
lexer so only use it when debug is True.
|
2015-03-06 23:53:25 +08:00
|
|
|
"""
|
2021-08-08 13:12:27 +08:00
|
|
|
# For maintainability, it is helpful if the implementation below can
|
|
|
|
# continue to closely parallel Lexer.tokenize()'s implementation.
|
|
|
|
in_tag = False
|
2015-03-06 23:53:25 +08:00
|
|
|
lineno = 1
|
|
|
|
result = []
|
2021-08-08 13:12:27 +08:00
|
|
|
for token_string, position in self._tag_re_split():
|
|
|
|
if token_string:
|
|
|
|
result.append(self.create_token(token_string, position, lineno, in_tag))
|
2015-03-06 23:53:25 +08:00
|
|
|
lineno += token_string.count('\n')
|
2021-08-08 13:12:27 +08:00
|
|
|
in_tag = not in_tag
|
2015-03-06 23:53:25 +08:00
|
|
|
return result
|
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class Parser:
|
2016-01-15 10:36:05 +08:00
|
|
|
def __init__(self, tokens, libraries=None, builtins=None, origin=None):
|
2019-10-09 10:25:20 +08:00
|
|
|
# Reverse the tokens so delete_first_token(), prepend_token(), and
|
|
|
|
# next_token() can operate at the end of the list in constant time.
|
|
|
|
self.tokens = list(reversed(tokens))
|
2010-11-27 13:47:30 +08:00
|
|
|
self.tags = {}
|
|
|
|
self.filters = {}
|
2015-03-06 23:53:25 +08:00
|
|
|
self.command_stack = []
|
2015-05-09 04:10:36 +08:00
|
|
|
|
|
|
|
if libraries is None:
|
|
|
|
libraries = {}
|
|
|
|
if builtins is None:
|
|
|
|
builtins = []
|
|
|
|
|
|
|
|
self.libraries = libraries
|
|
|
|
for builtin in builtins:
|
|
|
|
self.add_library(builtin)
|
2016-01-15 10:36:05 +08:00
|
|
|
self.origin = origin
|
2010-11-27 13:47:30 +08:00
|
|
|
|
2021-01-30 03:21:26 +08:00
|
|
|
def __repr__(self):
|
|
|
|
return '<%s tokens=%r>' % (self.__class__.__qualname__, self.tokens)
|
|
|
|
|
2010-11-27 13:47:30 +08:00
|
|
|
def parse(self, parse_until=None):
|
2015-03-06 23:53:25 +08:00
|
|
|
"""
|
2015-11-21 08:50:03 +08:00
|
|
|
Iterate through the parser tokens and compiles each one into a node.
|
2015-03-06 23:53:25 +08:00
|
|
|
|
|
|
|
If parse_until is provided, parsing will stop once one of the
|
|
|
|
specified tokens has been reached. This is formatted as a list of
|
|
|
|
tokens, e.g. ['elif', 'else', 'endif']. If no matching token is
|
|
|
|
reached, raise an exception with the unclosed block tag details.
|
|
|
|
"""
|
2011-09-27 20:15:15 +08:00
|
|
|
if parse_until is None:
|
|
|
|
parse_until = []
|
2015-03-06 23:53:25 +08:00
|
|
|
nodelist = NodeList()
|
2010-11-27 13:47:30 +08:00
|
|
|
while self.tokens:
|
|
|
|
token = self.next_token()
|
2018-05-10 23:51:51 +08:00
|
|
|
# Use the raw values here for TokenType.* for a tiny performance boost.
|
2021-07-06 21:53:03 +08:00
|
|
|
token_type = token.token_type.value
|
|
|
|
if token_type == 0: # TokenType.TEXT
|
2010-11-27 13:47:30 +08:00
|
|
|
self.extend_nodelist(nodelist, TextNode(token.contents), token)
|
2021-07-06 21:53:03 +08:00
|
|
|
elif token_type == 1: # TokenType.VAR
|
2010-11-27 13:47:30 +08:00
|
|
|
if not token.contents:
|
2015-09-11 11:05:00 +08:00
|
|
|
raise self.error(token, 'Empty variable tag on line %d' % token.lineno)
|
2013-02-14 16:45:55 +08:00
|
|
|
try:
|
|
|
|
filter_expression = self.compile_filter(token.contents)
|
|
|
|
except TemplateSyntaxError as e:
|
2015-03-06 23:53:25 +08:00
|
|
|
raise self.error(token, e)
|
|
|
|
var_node = VariableNode(filter_expression)
|
2011-09-27 20:15:15 +08:00
|
|
|
self.extend_nodelist(nodelist, var_node, token)
|
2021-07-06 21:53:03 +08:00
|
|
|
elif token_type == 2: # TokenType.BLOCK
|
2010-11-27 13:47:30 +08:00
|
|
|
try:
|
|
|
|
command = token.contents.split()[0]
|
|
|
|
except IndexError:
|
2015-09-11 11:05:00 +08:00
|
|
|
raise self.error(token, 'Empty block tag on line %d' % token.lineno)
|
2011-12-10 06:10:52 +08:00
|
|
|
if command in parse_until:
|
2015-03-06 23:53:25 +08:00
|
|
|
# A matching token has been reached. Return control to
|
|
|
|
# the caller. Put the token back on the token list so the
|
|
|
|
# caller knows where it terminated.
|
2011-12-10 06:10:52 +08:00
|
|
|
self.prepend_token(token)
|
|
|
|
return nodelist
|
2015-03-06 23:53:25 +08:00
|
|
|
# Add the token to the command stack. This is used for error
|
|
|
|
# messages if further parsing fails due to an unclosed block
|
|
|
|
# tag.
|
|
|
|
self.command_stack.append((command, token))
|
|
|
|
# Get the tag callback function from the ones registered with
|
|
|
|
# the parser.
|
2010-11-27 13:47:30 +08:00
|
|
|
try:
|
|
|
|
compile_func = self.tags[command]
|
|
|
|
except KeyError:
|
|
|
|
self.invalid_block_tag(token, command, parse_until)
|
2015-03-06 23:53:25 +08:00
|
|
|
# Compile the callback into a node object and add it to
|
|
|
|
# the node list.
|
2010-11-27 13:47:30 +08:00
|
|
|
try:
|
|
|
|
compiled_result = compile_func(self, token)
|
2015-03-06 23:53:25 +08:00
|
|
|
except Exception as e:
|
|
|
|
raise self.error(token, e)
|
2010-11-27 13:47:30 +08:00
|
|
|
self.extend_nodelist(nodelist, compiled_result, token)
|
2015-03-06 23:53:25 +08:00
|
|
|
# Compile success. Remove the token from the command stack.
|
|
|
|
self.command_stack.pop()
|
2010-11-27 13:47:30 +08:00
|
|
|
if parse_until:
|
|
|
|
self.unclosed_block_tag(parse_until)
|
|
|
|
return nodelist
|
|
|
|
|
|
|
|
def skip_past(self, endtag):
|
|
|
|
while self.tokens:
|
|
|
|
token = self.next_token()
|
2018-05-10 23:51:51 +08:00
|
|
|
if token.token_type == TokenType.BLOCK and token.contents == endtag:
|
2010-11-27 13:47:30 +08:00
|
|
|
return
|
|
|
|
self.unclosed_block_tag([endtag])
|
|
|
|
|
|
|
|
def extend_nodelist(self, nodelist, node, token):
|
2015-03-06 23:53:25 +08:00
|
|
|
# Check that non-text nodes don't appear before an extends tag.
|
|
|
|
if node.must_be_first and nodelist.contains_nontext:
|
|
|
|
raise self.error(
|
|
|
|
token, '%r must be the first tag in the template.' % node,
|
|
|
|
)
|
2021-07-06 21:53:03 +08:00
|
|
|
if not isinstance(node, TextNode):
|
2010-11-27 13:47:30 +08:00
|
|
|
nodelist.contains_nontext = True
|
2016-01-15 10:36:05 +08:00
|
|
|
# Set origin and token here since we can't modify the node __init__()
|
|
|
|
# method.
|
2015-03-06 23:53:25 +08:00
|
|
|
node.token = token
|
2016-01-15 10:36:05 +08:00
|
|
|
node.origin = self.origin
|
2010-11-27 13:47:30 +08:00
|
|
|
nodelist.append(node)
|
|
|
|
|
2015-03-06 23:53:25 +08:00
|
|
|
def error(self, token, e):
|
|
|
|
"""
|
|
|
|
Return an exception annotated with the originating token. Since the
|
|
|
|
parser can be called recursively, check if a token is already set. This
|
|
|
|
ensures the innermost token is highlighted if an exception occurs,
|
|
|
|
e.g. a compile error within the body of an if statement.
|
|
|
|
"""
|
|
|
|
if not isinstance(e, Exception):
|
|
|
|
e = TemplateSyntaxError(e)
|
|
|
|
if not hasattr(e, 'token'):
|
|
|
|
e.token = token
|
|
|
|
return e
|
2010-11-27 13:47:30 +08:00
|
|
|
|
|
|
|
def invalid_block_tag(self, token, command, parse_until=None):
|
|
|
|
if parse_until:
|
2015-09-11 11:05:00 +08:00
|
|
|
raise self.error(
|
|
|
|
token,
|
2015-10-05 01:50:18 +08:00
|
|
|
"Invalid block tag on line %d: '%s', expected %s. Did you "
|
|
|
|
"forget to register or load this tag?" % (
|
2015-09-11 11:05:00 +08:00
|
|
|
token.lineno,
|
|
|
|
command,
|
2016-04-03 16:02:20 +08:00
|
|
|
get_text_list(["'%s'" % p for p in parse_until], 'or'),
|
2015-09-11 11:05:00 +08:00
|
|
|
),
|
|
|
|
)
|
2015-10-05 01:50:18 +08:00
|
|
|
raise self.error(
|
|
|
|
token,
|
|
|
|
"Invalid block tag on line %d: '%s'. Did you forget to register "
|
|
|
|
"or load this tag?" % (token.lineno, command)
|
|
|
|
)
|
2010-11-27 13:47:30 +08:00
|
|
|
|
|
|
|
def unclosed_block_tag(self, parse_until):
|
2015-03-06 23:53:25 +08:00
|
|
|
command, token = self.command_stack.pop()
|
2015-09-11 11:05:00 +08:00
|
|
|
msg = "Unclosed tag on line %d: '%s'. Looking for one of: %s." % (
|
|
|
|
token.lineno,
|
|
|
|
command,
|
|
|
|
', '.join(parse_until),
|
|
|
|
)
|
2015-03-06 23:53:25 +08:00
|
|
|
raise self.error(token, msg)
|
2010-11-27 13:47:30 +08:00
|
|
|
|
|
|
|
def next_token(self):
|
2019-10-09 10:25:20 +08:00
|
|
|
return self.tokens.pop()
|
2010-11-27 13:47:30 +08:00
|
|
|
|
|
|
|
def prepend_token(self, token):
|
2019-10-09 10:25:20 +08:00
|
|
|
self.tokens.append(token)
|
2010-11-27 13:47:30 +08:00
|
|
|
|
|
|
|
def delete_first_token(self):
|
2019-10-09 10:25:20 +08:00
|
|
|
del self.tokens[-1]
|
2010-11-27 13:47:30 +08:00
|
|
|
|
|
|
|
def add_library(self, lib):
|
|
|
|
self.tags.update(lib.tags)
|
|
|
|
self.filters.update(lib.filters)
|
|
|
|
|
|
|
|
def compile_filter(self, token):
|
2011-09-27 20:15:15 +08:00
|
|
|
"""
|
|
|
|
Convenient wrapper for FilterExpression
|
|
|
|
"""
|
2010-11-27 13:47:30 +08:00
|
|
|
return FilterExpression(token, self)
|
|
|
|
|
|
|
|
def find_filter(self, filter_name):
|
|
|
|
if filter_name in self.filters:
|
|
|
|
return self.filters[filter_name]
|
|
|
|
else:
|
|
|
|
raise TemplateSyntaxError("Invalid filter: '%s'" % filter_name)
|
|
|
|
|
2013-11-03 08:37:15 +08:00
|
|
|
|
2010-11-27 13:47:30 +08:00
|
|
|
# This only matches constant *strings* (things in quotes or marked for
|
|
|
|
# translation). Numbers are treated as variables for implementation reasons
|
|
|
|
# (so that they retain their type when passed to filters).
|
|
|
|
constant_string = r"""
|
|
|
|
(?:%(i18n_open)s%(strdq)s%(i18n_close)s|
|
|
|
|
%(i18n_open)s%(strsq)s%(i18n_close)s|
|
|
|
|
%(strdq)s|
|
|
|
|
%(strsq)s)
|
|
|
|
""" % {
|
2011-09-27 20:15:15 +08:00
|
|
|
'strdq': r'"[^"\\]*(?:\\.[^"\\]*)*"', # double-quoted string
|
|
|
|
'strsq': r"'[^'\\]*(?:\\.[^'\\]*)*'", # single-quoted string
|
|
|
|
'i18n_open': re.escape("_("),
|
|
|
|
'i18n_close': re.escape(")"),
|
2013-10-18 17:02:43 +08:00
|
|
|
}
|
2010-11-27 13:47:30 +08:00
|
|
|
constant_string = constant_string.replace("\n", "")
|
|
|
|
|
|
|
|
filter_raw_string = r"""
|
|
|
|
^(?P<constant>%(constant)s)|
|
|
|
|
^(?P<var>[%(var_chars)s]+|%(num)s)|
|
2012-05-01 03:01:06 +08:00
|
|
|
(?:\s*%(filter_sep)s\s*
|
2010-11-27 13:47:30 +08:00
|
|
|
(?P<filter_name>\w+)
|
|
|
|
(?:%(arg_sep)s
|
|
|
|
(?:
|
|
|
|
(?P<constant_arg>%(constant)s)|
|
|
|
|
(?P<var_arg>[%(var_chars)s]+|%(num)s)
|
|
|
|
)
|
|
|
|
)?
|
|
|
|
)""" % {
|
|
|
|
'constant': constant_string,
|
|
|
|
'num': r'[-+\.]?\d[\d\.e]*',
|
2016-09-17 00:15:00 +08:00
|
|
|
'var_chars': r'\w\.',
|
2010-11-27 13:47:30 +08:00
|
|
|
'filter_sep': re.escape(FILTER_SEPARATOR),
|
|
|
|
'arg_sep': re.escape(FILTER_ARGUMENT_SEPARATOR),
|
2013-10-18 06:27:45 +08:00
|
|
|
}
|
2010-11-27 13:47:30 +08:00
|
|
|
|
2019-10-26 22:42:32 +08:00
|
|
|
filter_re = _lazy_re_compile(filter_raw_string, re.VERBOSE)
|
2010-11-27 13:47:30 +08:00
|
|
|
|
2013-11-03 08:37:15 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class FilterExpression:
|
2011-09-27 20:15:15 +08:00
|
|
|
"""
|
2017-01-25 04:36:36 +08:00
|
|
|
Parse a variable token and its optional filters (all as a single string),
|
2010-11-27 13:47:30 +08:00
|
|
|
and return a list of tuples of the filter name and arguments.
|
2011-09-27 20:15:15 +08:00
|
|
|
Sample::
|
|
|
|
|
2010-11-27 13:47:30 +08:00
|
|
|
>>> token = 'variable|default:"Default value"|date:"Y-m-d"'
|
|
|
|
>>> p = Parser('')
|
|
|
|
>>> fe = FilterExpression(token, p)
|
|
|
|
>>> len(fe.filters)
|
|
|
|
2
|
|
|
|
>>> fe.var
|
|
|
|
<Variable: 'variable'>
|
|
|
|
"""
|
|
|
|
def __init__(self, token, parser):
|
|
|
|
self.token = token
|
|
|
|
matches = filter_re.finditer(token)
|
|
|
|
var_obj = None
|
|
|
|
filters = []
|
|
|
|
upto = 0
|
|
|
|
for match in matches:
|
|
|
|
start = match.start()
|
|
|
|
if upto != start:
|
2011-09-27 20:15:15 +08:00
|
|
|
raise TemplateSyntaxError("Could not parse some characters: "
|
|
|
|
"%s|%s|%s" %
|
|
|
|
(token[:upto], token[upto:start],
|
|
|
|
token[start:]))
|
2010-11-27 13:47:30 +08:00
|
|
|
if var_obj is None:
|
2020-05-11 04:03:39 +08:00
|
|
|
var, constant = match['var'], match['constant']
|
2010-11-27 13:47:30 +08:00
|
|
|
if constant:
|
|
|
|
try:
|
|
|
|
var_obj = Variable(constant).resolve({})
|
|
|
|
except VariableDoesNotExist:
|
|
|
|
var_obj = None
|
|
|
|
elif var is None:
|
2011-09-27 20:15:15 +08:00
|
|
|
raise TemplateSyntaxError("Could not find variable at "
|
|
|
|
"start of %s." % token)
|
2010-11-27 13:47:30 +08:00
|
|
|
else:
|
|
|
|
var_obj = Variable(var)
|
|
|
|
else:
|
2020-05-11 04:03:39 +08:00
|
|
|
filter_name = match['filter_name']
|
2010-11-27 13:47:30 +08:00
|
|
|
args = []
|
2020-05-11 04:03:39 +08:00
|
|
|
constant_arg, var_arg = match['constant_arg'], match['var_arg']
|
2010-11-27 13:47:30 +08:00
|
|
|
if constant_arg:
|
|
|
|
args.append((False, Variable(constant_arg).resolve({})))
|
|
|
|
elif var_arg:
|
|
|
|
args.append((True, Variable(var_arg)))
|
|
|
|
filter_func = parser.find_filter(filter_name)
|
|
|
|
self.args_check(filter_name, filter_func, args)
|
|
|
|
filters.append((filter_func, args))
|
|
|
|
upto = match.end()
|
|
|
|
if upto != len(token):
|
2011-09-27 20:15:15 +08:00
|
|
|
raise TemplateSyntaxError("Could not parse the remainder: '%s' "
|
|
|
|
"from '%s'" % (token[upto:], token))
|
2010-11-27 13:47:30 +08:00
|
|
|
|
|
|
|
self.filters = filters
|
|
|
|
self.var = var_obj
|
|
|
|
|
|
|
|
def resolve(self, context, ignore_failures=False):
|
|
|
|
if isinstance(self.var, Variable):
|
|
|
|
try:
|
|
|
|
obj = self.var.resolve(context)
|
|
|
|
except VariableDoesNotExist:
|
|
|
|
if ignore_failures:
|
|
|
|
obj = None
|
|
|
|
else:
|
2015-02-18 05:49:59 +08:00
|
|
|
string_if_invalid = context.template.engine.string_if_invalid
|
2014-11-23 01:52:55 +08:00
|
|
|
if string_if_invalid:
|
|
|
|
if '%s' in string_if_invalid:
|
|
|
|
return string_if_invalid % self.var
|
|
|
|
else:
|
|
|
|
return string_if_invalid
|
2010-11-27 13:47:30 +08:00
|
|
|
else:
|
2014-11-23 01:52:55 +08:00
|
|
|
obj = string_if_invalid
|
2010-11-27 13:47:30 +08:00
|
|
|
else:
|
|
|
|
obj = self.var
|
|
|
|
for func, args in self.filters:
|
|
|
|
arg_vals = []
|
|
|
|
for lookup, arg in args:
|
|
|
|
if not lookup:
|
|
|
|
arg_vals.append(mark_safe(arg))
|
|
|
|
else:
|
|
|
|
arg_vals.append(arg.resolve(context))
|
2011-11-18 21:01:06 +08:00
|
|
|
if getattr(func, 'expects_localtime', False):
|
2012-04-29 21:37:23 +08:00
|
|
|
obj = template_localtime(obj, context.use_tz)
|
2010-11-27 13:47:30 +08:00
|
|
|
if getattr(func, 'needs_autoescape', False):
|
|
|
|
new_obj = func(obj, autoescape=context.autoescape, *arg_vals)
|
|
|
|
else:
|
|
|
|
new_obj = func(obj, *arg_vals)
|
|
|
|
if getattr(func, 'is_safe', False) and isinstance(obj, SafeData):
|
|
|
|
obj = mark_safe(new_obj)
|
|
|
|
else:
|
|
|
|
obj = new_obj
|
|
|
|
return obj
|
|
|
|
|
|
|
|
def args_check(name, func, provided):
|
|
|
|
provided = list(provided)
|
2013-09-04 18:53:55 +08:00
|
|
|
# First argument, filter input, is implied.
|
|
|
|
plen = len(provided) + 1
|
2010-11-27 13:47:30 +08:00
|
|
|
# Check to see if a decorator is providing the real function.
|
2019-12-10 00:33:51 +08:00
|
|
|
func = inspect.unwrap(func)
|
2015-06-11 05:24:04 +08:00
|
|
|
|
2019-12-10 00:33:51 +08:00
|
|
|
args, _, _, defaults, _, _, _ = inspect.getfullargspec(func)
|
2013-09-04 18:53:55 +08:00
|
|
|
alen = len(args)
|
|
|
|
dlen = len(defaults or [])
|
|
|
|
# Not enough OR Too many
|
|
|
|
if plen < (alen - dlen) or plen > alen:
|
2011-09-27 20:15:15 +08:00
|
|
|
raise TemplateSyntaxError("%s requires %d arguments, %d provided" %
|
2013-09-04 18:53:55 +08:00
|
|
|
(name, alen - dlen, plen))
|
2010-11-27 13:47:30 +08:00
|
|
|
|
|
|
|
return True
|
|
|
|
args_check = staticmethod(args_check)
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return self.token
|
|
|
|
|
2021-01-30 03:21:26 +08:00
|
|
|
def __repr__(self):
|
|
|
|
return "<%s %r>" % (self.__class__.__qualname__, self.token)
|
|
|
|
|
2013-11-03 08:37:15 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class Variable:
|
2011-09-27 20:15:15 +08:00
|
|
|
"""
|
|
|
|
A template variable, resolvable against a given context. The variable may
|
|
|
|
be a hard-coded string (if it begins and ends with single or double quote
|
2010-11-27 13:47:30 +08:00
|
|
|
marks)::
|
|
|
|
|
2015-07-06 21:17:28 +08:00
|
|
|
>>> c = {'article': {'section':'News'}}
|
2010-11-27 13:47:30 +08:00
|
|
|
>>> Variable('article.section').resolve(c)
|
2015-07-06 21:17:28 +08:00
|
|
|
'News'
|
2010-11-27 13:47:30 +08:00
|
|
|
>>> Variable('article').resolve(c)
|
2015-07-06 21:17:28 +08:00
|
|
|
{'section': 'News'}
|
2010-11-27 13:47:30 +08:00
|
|
|
>>> class AClass: pass
|
|
|
|
>>> c = AClass()
|
|
|
|
>>> c.article = AClass()
|
2015-07-06 21:17:28 +08:00
|
|
|
>>> c.article.section = 'News'
|
2010-11-27 13:47:30 +08:00
|
|
|
|
|
|
|
(The example assumes VARIABLE_ATTRIBUTE_SEPARATOR is '.')
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, var):
|
|
|
|
self.var = var
|
|
|
|
self.literal = None
|
|
|
|
self.lookups = None
|
|
|
|
self.translate = False
|
2011-10-19 12:59:47 +08:00
|
|
|
self.message_context = None
|
2010-11-27 13:47:30 +08:00
|
|
|
|
2016-12-29 23:27:49 +08:00
|
|
|
if not isinstance(var, str):
|
2013-09-19 21:27:19 +08:00
|
|
|
raise TypeError(
|
|
|
|
"Variable must be a string or number, got %s" % type(var))
|
2010-11-27 13:47:30 +08:00
|
|
|
try:
|
|
|
|
# First try to treat this variable as a number.
|
|
|
|
#
|
|
|
|
# Note that this could cause an OverflowError here that we're not
|
|
|
|
# catching. Since this should only happen at compile time, that's
|
|
|
|
# probably OK.
|
|
|
|
|
2018-08-02 00:55:53 +08:00
|
|
|
# Try to interpret values containing a period or an 'e'/'E'
|
2017-10-21 18:24:20 +08:00
|
|
|
# (possibly scientific notation) as a float; otherwise, try int.
|
|
|
|
if '.' in var or 'e' in var.lower():
|
|
|
|
self.literal = float(var)
|
|
|
|
# "2." is invalid
|
2021-07-06 21:53:03 +08:00
|
|
|
if var[-1] == '.':
|
2017-10-21 18:24:20 +08:00
|
|
|
raise ValueError
|
|
|
|
else:
|
|
|
|
self.literal = int(var)
|
2010-11-27 13:47:30 +08:00
|
|
|
except ValueError:
|
|
|
|
# A ValueError means that the variable isn't a number.
|
2021-07-06 21:53:03 +08:00
|
|
|
if var[0:2] == '_(' and var[-1] == ')':
|
2010-11-27 13:47:30 +08:00
|
|
|
# The result of the lookup should be translated at rendering
|
|
|
|
# time.
|
|
|
|
self.translate = True
|
|
|
|
var = var[2:-1]
|
|
|
|
# If it's wrapped with quotes (single or double), then
|
|
|
|
# we're also dealing with a literal.
|
|
|
|
try:
|
|
|
|
self.literal = mark_safe(unescape_string_literal(var))
|
|
|
|
except ValueError:
|
|
|
|
# Otherwise we'll set self.lookups so that resolve() knows we're
|
|
|
|
# dealing with a bonafide variable
|
2021-07-06 21:53:03 +08:00
|
|
|
if VARIABLE_ATTRIBUTE_SEPARATOR + '_' in var or var[0] == '_':
|
2011-09-27 20:15:15 +08:00
|
|
|
raise TemplateSyntaxError("Variables and attributes may "
|
|
|
|
"not begin with underscores: '%s'" %
|
|
|
|
var)
|
2010-11-27 13:47:30 +08:00
|
|
|
self.lookups = tuple(var.split(VARIABLE_ATTRIBUTE_SEPARATOR))
|
|
|
|
|
|
|
|
def resolve(self, context):
|
|
|
|
"""Resolve this variable against a given context."""
|
|
|
|
if self.lookups is not None:
|
|
|
|
# We're dealing with a variable that needs to be resolved
|
|
|
|
value = self._resolve_lookup(context)
|
|
|
|
else:
|
|
|
|
# We're dealing with a literal, so it's already been "resolved"
|
|
|
|
value = self.literal
|
|
|
|
if self.translate:
|
2015-04-16 05:01:11 +08:00
|
|
|
is_safe = isinstance(value, SafeData)
|
|
|
|
msgid = value.replace('%', '%%')
|
|
|
|
msgid = mark_safe(msgid) if is_safe else msgid
|
2011-10-19 12:59:47 +08:00
|
|
|
if self.message_context:
|
2015-04-16 05:01:11 +08:00
|
|
|
return pgettext_lazy(self.message_context, msgid)
|
2011-10-19 12:59:47 +08:00
|
|
|
else:
|
2017-01-27 03:58:33 +08:00
|
|
|
return gettext_lazy(msgid)
|
2010-11-27 13:47:30 +08:00
|
|
|
return value
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return "<%s: %r>" % (self.__class__.__name__, self.var)
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return self.var
|
|
|
|
|
|
|
|
def _resolve_lookup(self, context):
|
|
|
|
"""
|
2017-01-25 04:36:36 +08:00
|
|
|
Perform resolution of a real variable (i.e. not a literal) against the
|
2010-11-27 13:47:30 +08:00
|
|
|
given context.
|
|
|
|
|
|
|
|
As indicated by the method's name, this method is an implementation
|
|
|
|
detail and shouldn't be called by external code. Use Variable.resolve()
|
|
|
|
instead.
|
|
|
|
"""
|
|
|
|
current = context
|
2011-09-27 20:15:15 +08:00
|
|
|
try: # catch-all for silent variable failures
|
2010-12-20 07:47:24 +08:00
|
|
|
for bit in self.lookups:
|
2011-09-27 20:15:15 +08:00
|
|
|
try: # dictionary lookup
|
2010-12-20 07:47:24 +08:00
|
|
|
current = current[bit]
|
2014-09-30 07:51:33 +08:00
|
|
|
# ValueError/IndexError are for numpy.array lookup on
|
|
|
|
# numpy < 1.9 and 1.9+ respectively
|
|
|
|
except (TypeError, AttributeError, KeyError, ValueError, IndexError):
|
2011-09-27 20:15:15 +08:00
|
|
|
try: # attribute lookup
|
2013-08-13 00:41:39 +08:00
|
|
|
# Don't return class attributes if the class is the context:
|
|
|
|
if isinstance(current, BaseContext) and getattr(type(current), bit):
|
|
|
|
raise AttributeError
|
2010-12-20 07:47:24 +08:00
|
|
|
current = getattr(current, bit)
|
2017-01-25 22:14:05 +08:00
|
|
|
except (TypeError, AttributeError):
|
2016-09-01 01:44:38 +08:00
|
|
|
# Reraise if the exception was raised by a @property
|
|
|
|
if not isinstance(current, BaseContext) and bit in dir(current):
|
2014-07-26 19:00:54 +08:00
|
|
|
raise
|
2011-09-27 20:15:15 +08:00
|
|
|
try: # list-index lookup
|
2010-12-20 07:47:24 +08:00
|
|
|
current = current[int(bit)]
|
2011-09-27 20:15:15 +08:00
|
|
|
except (IndexError, # list index out of range
|
|
|
|
ValueError, # invalid literal for int()
|
|
|
|
KeyError, # current is a dict without `int(bit)` key
|
|
|
|
TypeError): # unsubscriptable object
|
|
|
|
raise VariableDoesNotExist("Failed lookup for key "
|
|
|
|
"[%s] in %r",
|
|
|
|
(bit, current)) # missing attribute
|
2010-12-20 07:47:24 +08:00
|
|
|
if callable(current):
|
2011-04-20 06:06:19 +08:00
|
|
|
if getattr(current, 'do_not_call_in_templates', False):
|
|
|
|
pass
|
|
|
|
elif getattr(current, 'alters_data', False):
|
2015-02-18 05:49:59 +08:00
|
|
|
current = context.template.engine.string_if_invalid
|
2010-11-27 13:47:30 +08:00
|
|
|
else:
|
2013-11-03 03:27:47 +08:00
|
|
|
try: # method call (assuming no args required)
|
2010-12-20 07:47:24 +08:00
|
|
|
current = current()
|
2013-09-08 21:07:12 +08:00
|
|
|
except TypeError:
|
2019-12-10 16:25:07 +08:00
|
|
|
signature = inspect.signature(current)
|
2013-09-08 21:07:12 +08:00
|
|
|
try:
|
2019-12-10 16:25:07 +08:00
|
|
|
signature.bind()
|
2013-11-03 03:27:47 +08:00
|
|
|
except TypeError: # arguments *were* required
|
2015-02-18 05:49:59 +08:00
|
|
|
current = context.template.engine.string_if_invalid # invalid method call
|
2013-09-08 21:07:12 +08:00
|
|
|
else:
|
|
|
|
raise
|
2012-04-29 00:09:37 +08:00
|
|
|
except Exception as e:
|
2015-09-22 03:20:19 +08:00
|
|
|
template_name = getattr(context, 'template_name', None) or 'unknown'
|
|
|
|
logger.debug(
|
|
|
|
"Exception while resolving variable '%s' in template '%s'.",
|
|
|
|
bit,
|
|
|
|
template_name,
|
|
|
|
exc_info=True,
|
|
|
|
)
|
2014-04-15 05:18:03 +08:00
|
|
|
|
2010-12-20 07:47:24 +08:00
|
|
|
if getattr(e, 'silent_variable_failure', False):
|
2015-02-18 05:49:59 +08:00
|
|
|
current = context.template.engine.string_if_invalid
|
2010-12-20 07:47:24 +08:00
|
|
|
else:
|
|
|
|
raise
|
2010-11-27 13:47:30 +08:00
|
|
|
|
|
|
|
return current
|
|
|
|
|
2013-11-03 08:37:15 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class Node:
|
2010-11-27 13:47:30 +08:00
|
|
|
# Set this to True for nodes that must be first in the template (although
|
|
|
|
# they can be preceded by text nodes.
|
|
|
|
must_be_first = False
|
|
|
|
child_nodelists = ('nodelist',)
|
2015-03-06 23:53:25 +08:00
|
|
|
token = None
|
2010-11-27 13:47:30 +08:00
|
|
|
|
|
|
|
def render(self, context):
|
2011-09-27 20:15:15 +08:00
|
|
|
"""
|
|
|
|
Return the node rendered as a string.
|
|
|
|
"""
|
2010-11-27 13:47:30 +08:00
|
|
|
pass
|
|
|
|
|
2015-03-06 23:53:25 +08:00
|
|
|
def render_annotated(self, context):
|
|
|
|
"""
|
|
|
|
Render the node. If debug is True and an exception occurs during
|
|
|
|
rendering, the exception is annotated with contextual line information
|
|
|
|
where it occurred in the template. For internal usage this method is
|
|
|
|
preferred over using the render method directly.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
return self.render(context)
|
|
|
|
except Exception as e:
|
2021-05-08 04:49:07 +08:00
|
|
|
if context.template.engine.debug:
|
|
|
|
# Store the actual node that caused the exception.
|
|
|
|
if not hasattr(e, '_culprit_node'):
|
|
|
|
e._culprit_node = self
|
|
|
|
if (
|
|
|
|
not hasattr(e, 'template_debug') and
|
|
|
|
context.render_context.template.origin == e._culprit_node.origin
|
|
|
|
):
|
|
|
|
e.template_debug = context.render_context.template.get_exception_info(
|
|
|
|
e, e._culprit_node.token,
|
|
|
|
)
|
2015-03-06 23:53:25 +08:00
|
|
|
raise
|
|
|
|
|
2010-11-27 13:47:30 +08:00
|
|
|
def __iter__(self):
|
|
|
|
yield self
|
|
|
|
|
|
|
|
def get_nodes_by_type(self, nodetype):
|
2011-09-27 20:15:15 +08:00
|
|
|
"""
|
|
|
|
Return a list of all nodes (within this node and its nodelist)
|
|
|
|
of the given type
|
|
|
|
"""
|
2010-11-27 13:47:30 +08:00
|
|
|
nodes = []
|
|
|
|
if isinstance(self, nodetype):
|
|
|
|
nodes.append(self)
|
|
|
|
for attr in self.child_nodelists:
|
|
|
|
nodelist = getattr(self, attr, None)
|
|
|
|
if nodelist:
|
|
|
|
nodes.extend(nodelist.get_nodes_by_type(nodetype))
|
|
|
|
return nodes
|
|
|
|
|
2013-11-03 08:37:15 +08:00
|
|
|
|
2010-11-27 13:47:30 +08:00
|
|
|
class NodeList(list):
|
|
|
|
# Set to True the first time a non-TextNode is inserted by
|
|
|
|
# extend_nodelist().
|
|
|
|
contains_nontext = False
|
|
|
|
|
|
|
|
def render(self, context):
|
2021-06-07 19:56:50 +08:00
|
|
|
return SafeString(''.join([
|
|
|
|
node.render_annotated(context) for node in self
|
|
|
|
]))
|
2010-11-27 13:47:30 +08:00
|
|
|
|
|
|
|
def get_nodes_by_type(self, nodetype):
|
|
|
|
"Return a list of all nodes of the given type"
|
|
|
|
nodes = []
|
|
|
|
for node in self:
|
|
|
|
nodes.extend(node.get_nodes_by_type(nodetype))
|
|
|
|
return nodes
|
|
|
|
|
2013-11-03 08:37:15 +08:00
|
|
|
|
2010-11-27 13:47:30 +08:00
|
|
|
class TextNode(Node):
|
2021-07-06 21:53:03 +08:00
|
|
|
child_nodelists = ()
|
|
|
|
|
2010-11-27 13:47:30 +08:00
|
|
|
def __init__(self, s):
|
|
|
|
self.s = s
|
|
|
|
|
|
|
|
def __repr__(self):
|
2017-01-12 06:17:25 +08:00
|
|
|
return "<%s: %r>" % (self.__class__.__name__, self.s[:25])
|
2010-11-27 13:47:30 +08:00
|
|
|
|
|
|
|
def render(self, context):
|
|
|
|
return self.s
|
|
|
|
|
2021-06-08 03:02:00 +08:00
|
|
|
def render_annotated(self, context):
|
|
|
|
"""
|
|
|
|
Return the given value.
|
|
|
|
|
|
|
|
The default implementation of this method handles exceptions raised
|
|
|
|
during rendering, which is not necessary for text nodes.
|
|
|
|
"""
|
|
|
|
return self.s
|
|
|
|
|
2013-11-03 08:37:15 +08:00
|
|
|
|
2013-02-25 15:33:29 +08:00
|
|
|
def render_value_in_context(value, context):
|
2010-11-27 13:47:30 +08:00
|
|
|
"""
|
2017-01-25 04:36:36 +08:00
|
|
|
Convert any value to a string to become part of a rendered template. This
|
2017-01-21 05:04:05 +08:00
|
|
|
means escaping, if required, and conversion to a string. If value is a
|
|
|
|
string, it's expected to already be translated.
|
2010-11-27 13:47:30 +08:00
|
|
|
"""
|
2012-04-29 21:37:23 +08:00
|
|
|
value = template_localtime(value, use_tz=context.use_tz)
|
2010-11-27 13:47:30 +08:00
|
|
|
value = localize(value, use_l10n=context.use_l10n)
|
2017-01-01 01:43:30 +08:00
|
|
|
if context.autoescape:
|
2017-02-07 16:17:38 +08:00
|
|
|
if not issubclass(type(value), str):
|
|
|
|
value = str(value)
|
2014-12-24 05:29:01 +08:00
|
|
|
return conditional_escape(value)
|
2010-11-27 13:47:30 +08:00
|
|
|
else:
|
2017-02-07 16:17:38 +08:00
|
|
|
return str(value)
|
2010-11-27 13:47:30 +08:00
|
|
|
|
2013-11-03 08:37:15 +08:00
|
|
|
|
2010-11-27 13:47:30 +08:00
|
|
|
class VariableNode(Node):
|
2021-07-06 21:53:03 +08:00
|
|
|
child_nodelists = ()
|
|
|
|
|
2010-11-27 13:47:30 +08:00
|
|
|
def __init__(self, filter_expression):
|
|
|
|
self.filter_expression = filter_expression
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return "<Variable Node: %s>" % self.filter_expression
|
|
|
|
|
|
|
|
def render(self, context):
|
|
|
|
try:
|
|
|
|
output = self.filter_expression.resolve(context)
|
|
|
|
except UnicodeDecodeError:
|
|
|
|
# Unicode conversion can fail sometimes for reasons out of our
|
2011-09-27 20:15:15 +08:00
|
|
|
# control (e.g. exception rendering). In that case, we fail
|
|
|
|
# quietly.
|
2010-11-27 13:47:30 +08:00
|
|
|
return ''
|
2013-02-25 15:33:29 +08:00
|
|
|
return render_value_in_context(output, context)
|
2010-11-27 13:47:30 +08:00
|
|
|
|
2016-11-13 01:11:23 +08:00
|
|
|
|
2011-09-27 20:15:15 +08:00
|
|
|
# Regex for token keyword arguments
|
2019-10-26 22:42:32 +08:00
|
|
|
kwarg_re = _lazy_re_compile(r"(?:(\w+)=)?(.+)")
|
2011-09-27 20:15:15 +08:00
|
|
|
|
2013-11-03 08:37:15 +08:00
|
|
|
|
2011-09-27 20:15:15 +08:00
|
|
|
def token_kwargs(bits, parser, support_legacy=False):
|
|
|
|
"""
|
2017-01-25 04:36:36 +08:00
|
|
|
Parse token keyword arguments and return a dictionary of the arguments
|
|
|
|
retrieved from the ``bits`` token list.
|
2011-09-27 20:15:15 +08:00
|
|
|
|
2017-01-25 04:36:36 +08:00
|
|
|
`bits` is a list containing the remainder of the token (split by spaces)
|
|
|
|
that is to be checked for arguments. Valid arguments are removed from this
|
|
|
|
list.
|
2011-09-27 20:15:15 +08:00
|
|
|
|
2017-01-25 04:36:36 +08:00
|
|
|
`support_legacy` - if True, the legacy format ``1 as foo`` is accepted.
|
|
|
|
Otherwise, only the standard ``foo=1`` format is allowed.
|
2011-09-27 20:15:15 +08:00
|
|
|
|
|
|
|
There is no requirement for all remaining token ``bits`` to be keyword
|
2017-01-25 04:36:36 +08:00
|
|
|
arguments, so return the dictionary as soon as an invalid argument format
|
|
|
|
is reached.
|
2011-09-27 20:15:15 +08:00
|
|
|
"""
|
|
|
|
if not bits:
|
|
|
|
return {}
|
|
|
|
match = kwarg_re.match(bits[0])
|
2020-05-11 04:03:39 +08:00
|
|
|
kwarg_format = match and match[1]
|
2011-09-27 20:15:15 +08:00
|
|
|
if not kwarg_format:
|
|
|
|
if not support_legacy:
|
|
|
|
return {}
|
|
|
|
if len(bits) < 3 or bits[1] != 'as':
|
|
|
|
return {}
|
|
|
|
|
|
|
|
kwargs = {}
|
|
|
|
while bits:
|
|
|
|
if kwarg_format:
|
|
|
|
match = kwarg_re.match(bits[0])
|
2020-05-11 04:03:39 +08:00
|
|
|
if not match or not match[1]:
|
2011-09-27 20:15:15 +08:00
|
|
|
return kwargs
|
|
|
|
key, value = match.groups()
|
|
|
|
del bits[:1]
|
|
|
|
else:
|
|
|
|
if len(bits) < 3 or bits[1] != 'as':
|
|
|
|
return kwargs
|
|
|
|
key, value = bits[2], bits[0]
|
|
|
|
del bits[:3]
|
|
|
|
kwargs[key] = parser.compile_filter(value)
|
|
|
|
if bits and not kwarg_format:
|
|
|
|
if bits[0] != 'and':
|
|
|
|
return kwargs
|
|
|
|
del bits[:1]
|
|
|
|
return kwargs
|