2005-07-13 09:25:57 +08:00
|
|
|
"""
|
2005-08-10 06:43:34 +08:00
|
|
|
This is the Django template system.
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
How it works:
|
|
|
|
|
2005-11-27 06:46:31 +08:00
|
|
|
The Lexer.tokenize() function converts a template string (i.e., a string containing
|
2005-07-13 09:25:57 +08:00
|
|
|
markup with custom template tags) to tokens, which can be either plain text
|
|
|
|
(TOKEN_TEXT), variables (TOKEN_VAR) or block statements (TOKEN_BLOCK).
|
|
|
|
|
|
|
|
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 an IfNode 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:
|
|
|
|
|
2007-09-15 16:29:56 +08:00
|
|
|
>>> from django import template
|
|
|
|
>>> s = u'<html>{% if test %}<h1>{{ varvalue }}</h1>{% endif %}</html>'
|
2005-07-13 09:25:57 +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)
|
2007-09-15 16:29:56 +08:00
|
|
|
u'<html><h1>Hello</h1></html>'
|
2005-07-13 09:25:57 +08:00
|
|
|
>>> c = template.Context({'test':False, 'varvalue': 'Hello'})
|
|
|
|
>>> t.render(c)
|
2007-09-15 16:29:56 +08:00
|
|
|
u'<html></html>'
|
2005-07-13 09:25:57 +08:00
|
|
|
"""
|
|
|
|
import re
|
2005-11-27 06:46:31 +08:00
|
|
|
from inspect import getargspec
|
2006-05-02 09:31:56 +08:00
|
|
|
from django.conf import settings
|
|
|
|
from django.template.context import Context, RequestContext, ContextPopException
|
2007-09-15 03:55:24 +08:00
|
|
|
from django.utils.itercompat import is_iterable
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
from django.utils.functional import curry, Promise
|
2006-06-08 12:29:10 +08:00
|
|
|
from django.utils.text import smart_split
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
from django.utils.encoding import smart_unicode, force_unicode
|
|
|
|
from django.utils.translation import ugettext as _
|
2007-11-14 20:58:53 +08:00
|
|
|
from django.utils.safestring import SafeData, EscapeData, mark_safe, mark_for_escaping
|
|
|
|
from django.utils.html import escape
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
__all__ = ('Template', 'Context', 'RequestContext', 'compile_string')
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
TOKEN_TEXT = 0
|
|
|
|
TOKEN_VAR = 1
|
|
|
|
TOKEN_BLOCK = 2
|
2006-10-25 05:30:38 +08:00
|
|
|
TOKEN_COMMENT = 3
|
2005-07-13 09:25:57 +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 = '}}'
|
2006-10-25 05:30:38 +08:00
|
|
|
COMMENT_TAG_START = '{#'
|
|
|
|
COMMENT_TAG_END = '#}'
|
2006-06-18 12:12:55 +08:00
|
|
|
SINGLE_BRACE_START = '{'
|
|
|
|
SINGLE_BRACE_END = '}'
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
ALLOWED_VARIABLE_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.'
|
|
|
|
|
2005-11-24 07:10:17 +08:00
|
|
|
# what to report as the origin for templates that come from non-loader sources
|
|
|
|
# (e.g. strings)
|
2005-11-27 08:01:11 +08:00
|
|
|
UNKNOWN_SOURCE="<unknown source>"
|
2005-11-24 07:10:17 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
# match a variable or block tag and capture the entire tag, including start/end delimiters
|
2006-10-25 05:30:38 +08:00
|
|
|
tag_re = re.compile('(%s.*?%s|%s.*?%s|%s.*?%s)' % (re.escape(BLOCK_TAG_START), re.escape(BLOCK_TAG_END),
|
|
|
|
re.escape(VARIABLE_TAG_START), re.escape(VARIABLE_TAG_END),
|
|
|
|
re.escape(COMMENT_TAG_START), re.escape(COMMENT_TAG_END)))
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2005-11-27 06:46:31 +08:00
|
|
|
# global dictionary of libraries that have been loaded using get_library
|
|
|
|
libraries = {}
|
|
|
|
# global list of libraries to load by default for a new parser
|
|
|
|
builtins = []
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2007-05-08 11:36:16 +08:00
|
|
|
# True if TEMPLATE_STRING_IF_INVALID contains a format string (%s). None means
|
|
|
|
# uninitialised.
|
|
|
|
invalid_var_format_string = None
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
class TemplateSyntaxError(Exception):
|
2006-05-15 12:24:48 +08:00
|
|
|
def __str__(self):
|
|
|
|
try:
|
|
|
|
import cStringIO as StringIO
|
|
|
|
except ImportError:
|
|
|
|
import StringIO
|
|
|
|
output = StringIO.StringIO()
|
|
|
|
output.write(Exception.__str__(self))
|
|
|
|
# Check if we wrapped an exception and print that too.
|
|
|
|
if hasattr(self, 'exc_info'):
|
|
|
|
import traceback
|
|
|
|
output.write('\n\nOriginal ')
|
|
|
|
e = self.exc_info
|
|
|
|
traceback.print_exception(e[0], e[1], e[2], 500, output)
|
|
|
|
return output.getvalue()
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
class TemplateDoesNotExist(Exception):
|
|
|
|
pass
|
|
|
|
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
class TemplateEncodingError(Exception):
|
|
|
|
pass
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
class VariableDoesNotExist(Exception):
|
|
|
|
|
2007-02-06 21:59:24 +08:00
|
|
|
def __init__(self, msg, params=()):
|
|
|
|
self.msg = msg
|
|
|
|
self.params = params
|
2007-04-25 15:05:31 +08:00
|
|
|
|
2007-02-06 21:59:24 +08:00
|
|
|
def __str__(self):
|
2008-03-17 22:21:09 +08:00
|
|
|
return unicode(self).encode('utf-8')
|
|
|
|
|
|
|
|
def __unicode__(self):
|
|
|
|
return self.msg % tuple([force_unicode(p, errors='replace') for p in self.params])
|
2007-04-25 15:05:31 +08:00
|
|
|
|
2005-11-27 06:46:31 +08:00
|
|
|
class InvalidTemplateLibrary(Exception):
|
|
|
|
pass
|
|
|
|
|
2005-11-24 07:10:17 +08:00
|
|
|
class Origin(object):
|
|
|
|
def __init__(self, name):
|
|
|
|
self.name = name
|
|
|
|
|
|
|
|
def reload(self):
|
2005-11-27 06:46:31 +08:00
|
|
|
raise NotImplementedError
|
2005-11-24 07:10:17 +08:00
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return self.name
|
|
|
|
|
|
|
|
class StringOrigin(Origin):
|
|
|
|
def __init__(self, source):
|
|
|
|
super(StringOrigin, self).__init__(UNKNOWN_SOURCE)
|
|
|
|
self.source = source
|
|
|
|
|
|
|
|
def reload(self):
|
|
|
|
return self.source
|
|
|
|
|
2006-06-08 13:00:13 +08:00
|
|
|
class Template(object):
|
2006-09-02 17:26:24 +08:00
|
|
|
def __init__(self, template_string, origin=None, name='<Unknown Template>'):
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
try:
|
|
|
|
template_string = smart_unicode(template_string)
|
|
|
|
except UnicodeDecodeError:
|
|
|
|
raise TemplateEncodingError("Templates can only be constructed from unicode or UTF-8 strings.")
|
2007-12-23 03:12:58 +08:00
|
|
|
if settings.TEMPLATE_DEBUG and origin is None:
|
2005-11-24 07:10:17 +08:00
|
|
|
origin = StringOrigin(template_string)
|
|
|
|
self.nodelist = compile_string(template_string, origin)
|
2006-09-02 17:26:24 +08:00
|
|
|
self.name = name
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
for node in self.nodelist:
|
|
|
|
for subnode in node:
|
|
|
|
yield subnode
|
|
|
|
|
2007-06-17 15:11:37 +08:00
|
|
|
def render(self, context):
|
2007-06-22 15:15:04 +08:00
|
|
|
"Display stage -- can be called many times"
|
|
|
|
return self.nodelist.render(context)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2005-11-24 07:10:17 +08:00
|
|
|
def compile_string(template_string, origin):
|
2005-07-13 09:25:57 +08:00
|
|
|
"Compiles template_string into NodeList ready for rendering"
|
2007-12-23 03:28:21 +08:00
|
|
|
if settings.TEMPLATE_DEBUG:
|
|
|
|
from debug import DebugLexer, DebugParser
|
|
|
|
lexer_class, parser_class = DebugLexer, DebugParser
|
|
|
|
else:
|
|
|
|
lexer_class, parser_class = Lexer, Parser
|
|
|
|
lexer = lexer_class(template_string, origin)
|
|
|
|
parser = parser_class(lexer.tokenize())
|
2005-07-13 09:25:57 +08:00
|
|
|
return parser.parse()
|
|
|
|
|
2006-06-08 13:00:13 +08:00
|
|
|
class Token(object):
|
2005-07-13 09:25:57 +08:00
|
|
|
def __init__(self, token_type, contents):
|
2007-12-23 03:30:13 +08:00
|
|
|
# token_type must be TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK or TOKEN_COMMENT.
|
2005-07-13 09:25:57 +08:00
|
|
|
self.token_type, self.contents = token_type, contents
|
|
|
|
|
|
|
|
def __str__(self):
|
2006-06-08 12:29:10 +08:00
|
|
|
return '<%s token: "%s...">' % \
|
2006-10-25 05:30:38 +08:00
|
|
|
({TOKEN_TEXT: 'Text', TOKEN_VAR: 'Var', TOKEN_BLOCK: 'Block', TOKEN_COMMENT: 'Comment'}[self.token_type],
|
2006-06-08 12:29:10 +08:00
|
|
|
self.contents[:20].replace('\n', ''))
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2006-06-08 12:29:10 +08:00
|
|
|
def split_contents(self):
|
2006-07-10 18:48:08 +08:00
|
|
|
return list(smart_split(self.contents))
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2005-11-24 07:10:17 +08:00
|
|
|
class Lexer(object):
|
|
|
|
def __init__(self, template_string, origin):
|
|
|
|
self.template_string = template_string
|
|
|
|
self.origin = origin
|
|
|
|
|
|
|
|
def tokenize(self):
|
2007-12-23 03:30:13 +08:00
|
|
|
"Return a list of tokens from a given template_string."
|
2007-04-27 20:16:22 +08:00
|
|
|
in_tag = False
|
|
|
|
result = []
|
|
|
|
for bit in tag_re.split(self.template_string):
|
|
|
|
if bit:
|
|
|
|
result.append(self.create_token(bit, in_tag))
|
|
|
|
in_tag = not in_tag
|
|
|
|
return result
|
|
|
|
|
2007-04-27 20:27:19 +08:00
|
|
|
def create_token(self, token_string, in_tag):
|
2007-04-27 20:16:22 +08:00
|
|
|
"""
|
|
|
|
Convert the given token string into a new Token object and return it.
|
2007-04-28 21:31:44 +08:00
|
|
|
If in_tag is True, we are processing something that matched a tag,
|
2007-04-27 20:16:22 +08:00
|
|
|
otherwise it should be treated as a literal string.
|
|
|
|
"""
|
|
|
|
if in_tag:
|
|
|
|
if token_string.startswith(VARIABLE_TAG_START):
|
|
|
|
token = Token(TOKEN_VAR, token_string[len(VARIABLE_TAG_START):-len(VARIABLE_TAG_END)].strip())
|
|
|
|
elif token_string.startswith(BLOCK_TAG_START):
|
|
|
|
token = Token(TOKEN_BLOCK, token_string[len(BLOCK_TAG_START):-len(BLOCK_TAG_END)].strip())
|
|
|
|
elif token_string.startswith(COMMENT_TAG_START):
|
|
|
|
token = Token(TOKEN_COMMENT, '')
|
2005-11-24 07:10:17 +08:00
|
|
|
else:
|
|
|
|
token = Token(TOKEN_TEXT, token_string)
|
|
|
|
return token
|
|
|
|
|
|
|
|
class Parser(object):
|
2005-07-13 09:25:57 +08:00
|
|
|
def __init__(self, tokens):
|
|
|
|
self.tokens = tokens
|
2005-11-27 06:46:31 +08:00
|
|
|
self.tags = {}
|
|
|
|
self.filters = {}
|
|
|
|
for lib in builtins:
|
|
|
|
self.add_library(lib)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2006-06-03 21:37:34 +08:00
|
|
|
def parse(self, parse_until=None):
|
|
|
|
if parse_until is None: parse_until = []
|
2005-11-24 07:10:17 +08:00
|
|
|
nodelist = self.create_nodelist()
|
2005-07-13 09:25:57 +08:00
|
|
|
while self.tokens:
|
|
|
|
token = self.next_token()
|
|
|
|
if token.token_type == TOKEN_TEXT:
|
2005-11-24 07:10:17 +08:00
|
|
|
self.extend_nodelist(nodelist, TextNode(token.contents), token)
|
2005-07-13 09:25:57 +08:00
|
|
|
elif token.token_type == TOKEN_VAR:
|
|
|
|
if not token.contents:
|
2005-11-24 07:10:17 +08:00
|
|
|
self.empty_variable(token)
|
2005-11-27 06:46:31 +08:00
|
|
|
filter_expression = self.compile_filter(token.contents)
|
|
|
|
var_node = self.create_variable_node(filter_expression)
|
2005-11-24 07:10:17 +08:00
|
|
|
self.extend_nodelist(nodelist, var_node,token)
|
2005-07-13 09:25:57 +08:00
|
|
|
elif token.token_type == TOKEN_BLOCK:
|
|
|
|
if token.contents in parse_until:
|
|
|
|
# put token back on token list so calling code knows why it terminated
|
|
|
|
self.prepend_token(token)
|
|
|
|
return nodelist
|
|
|
|
try:
|
|
|
|
command = token.contents.split()[0]
|
|
|
|
except IndexError:
|
2005-11-24 07:10:17 +08:00
|
|
|
self.empty_block_tag(token)
|
|
|
|
# execute callback function for this tag and append resulting node
|
|
|
|
self.enter_command(command, token)
|
2005-07-13 09:25:57 +08:00
|
|
|
try:
|
2005-11-27 06:46:31 +08:00
|
|
|
compile_func = self.tags[command]
|
2005-07-13 09:25:57 +08:00
|
|
|
except KeyError:
|
2005-11-24 07:10:17 +08:00
|
|
|
self.invalid_block_tag(token, command)
|
|
|
|
try:
|
|
|
|
compiled_result = compile_func(self, token)
|
|
|
|
except TemplateSyntaxError, e:
|
|
|
|
if not self.compile_function_error(token, e):
|
2006-05-02 09:31:56 +08:00
|
|
|
raise
|
2005-11-24 07:10:17 +08:00
|
|
|
self.extend_nodelist(nodelist, compiled_result, token)
|
|
|
|
self.exit_command()
|
2005-07-13 09:25:57 +08:00
|
|
|
if parse_until:
|
2005-11-24 07:10:17 +08:00
|
|
|
self.unclosed_block_tag(parse_until)
|
2005-07-13 09:25:57 +08:00
|
|
|
return nodelist
|
|
|
|
|
2006-01-15 08:48:23 +08:00
|
|
|
def skip_past(self, endtag):
|
|
|
|
while self.tokens:
|
|
|
|
token = self.next_token()
|
|
|
|
if token.token_type == TOKEN_BLOCK and token.contents == endtag:
|
|
|
|
return
|
|
|
|
self.unclosed_block_tag([endtag])
|
|
|
|
|
2005-11-27 06:46:31 +08:00
|
|
|
def create_variable_node(self, filter_expression):
|
|
|
|
return VariableNode(filter_expression)
|
2005-11-24 07:10:17 +08:00
|
|
|
|
|
|
|
def create_nodelist(self):
|
|
|
|
return NodeList()
|
|
|
|
|
|
|
|
def extend_nodelist(self, nodelist, node, token):
|
2008-02-06 07:41:48 +08:00
|
|
|
if node.must_be_first and nodelist:
|
|
|
|
try:
|
|
|
|
if nodelist.contains_nontext:
|
|
|
|
raise AttributeError
|
|
|
|
except AttributeError:
|
|
|
|
raise TemplateSyntaxError("%r must be the first tag in the template." % node)
|
|
|
|
if isinstance(nodelist, NodeList) and not isinstance(node, TextNode):
|
|
|
|
nodelist.contains_nontext = True
|
2005-11-24 07:10:17 +08:00
|
|
|
nodelist.append(node)
|
|
|
|
|
|
|
|
def enter_command(self, command, token):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def exit_command(self):
|
|
|
|
pass
|
|
|
|
|
2007-12-23 03:30:13 +08:00
|
|
|
def error(self, token, msg):
|
2005-11-24 07:10:17 +08:00
|
|
|
return TemplateSyntaxError(msg)
|
|
|
|
|
|
|
|
def empty_variable(self, token):
|
2007-12-23 03:16:39 +08:00
|
|
|
raise self.error(token, "Empty variable tag")
|
2005-11-24 07:10:17 +08:00
|
|
|
|
|
|
|
def empty_block_tag(self, token):
|
2007-12-23 03:16:39 +08:00
|
|
|
raise self.error(token, "Empty block tag")
|
2005-11-24 07:10:17 +08:00
|
|
|
|
|
|
|
def invalid_block_tag(self, token, command):
|
2007-12-23 03:16:39 +08:00
|
|
|
raise self.error(token, "Invalid block tag: '%s'" % command)
|
2005-11-24 07:10:17 +08:00
|
|
|
|
|
|
|
def unclosed_block_tag(self, parse_until):
|
|
|
|
raise self.error(None, "Unclosed tags: %s " % ', '.join(parse_until))
|
|
|
|
|
|
|
|
def compile_function_error(self, token, e):
|
|
|
|
pass
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
def next_token(self):
|
|
|
|
return self.tokens.pop(0)
|
|
|
|
|
|
|
|
def prepend_token(self, token):
|
|
|
|
self.tokens.insert(0, token)
|
|
|
|
|
|
|
|
def delete_first_token(self):
|
|
|
|
del self.tokens[0]
|
|
|
|
|
2005-11-27 06:46:31 +08:00
|
|
|
def add_library(self, lib):
|
|
|
|
self.tags.update(lib.tags)
|
|
|
|
self.filters.update(lib.filters)
|
|
|
|
|
2006-07-04 11:21:44 +08:00
|
|
|
def compile_filter(self, token):
|
2005-11-27 06:46:31 +08:00
|
|
|
"Convenient wrapper for FilterExpression"
|
|
|
|
return FilterExpression(token, self)
|
|
|
|
|
|
|
|
def find_filter(self, filter_name):
|
2007-04-26 21:30:48 +08:00
|
|
|
if filter_name in self.filters:
|
2005-11-27 06:46:31 +08:00
|
|
|
return self.filters[filter_name]
|
|
|
|
else:
|
2007-12-23 03:16:39 +08:00
|
|
|
raise TemplateSyntaxError("Invalid filter: '%s'" % filter_name)
|
2005-11-27 06:46:31 +08:00
|
|
|
|
2006-06-08 13:00:13 +08:00
|
|
|
class TokenParser(object):
|
2005-11-04 12:59:46 +08:00
|
|
|
"""
|
2005-11-07 06:22:02 +08:00
|
|
|
Subclass this and implement the top() method to parse a template line. When
|
|
|
|
instantiating the parser, pass in the line from the Django template parser.
|
2005-11-04 12:59:46 +08:00
|
|
|
|
2005-11-07 06:22:02 +08:00
|
|
|
The parser's "tagname" instance-variable stores the name of the tag that
|
|
|
|
the filter was called with.
|
2005-11-04 12:59:46 +08:00
|
|
|
"""
|
|
|
|
def __init__(self, subject):
|
|
|
|
self.subject = subject
|
|
|
|
self.pointer = 0
|
|
|
|
self.backout = []
|
|
|
|
self.tagname = self.tag()
|
|
|
|
|
|
|
|
def top(self):
|
2005-11-07 06:22:02 +08:00
|
|
|
"Overload this method to do the actual parsing and return the result."
|
2007-12-23 03:16:39 +08:00
|
|
|
raise NotImplementedError()
|
2005-11-04 12:59:46 +08:00
|
|
|
|
|
|
|
def more(self):
|
2005-11-07 06:22:02 +08:00
|
|
|
"Returns True if there is more stuff in the tag."
|
2005-11-04 12:59:46 +08:00
|
|
|
return self.pointer < len(self.subject)
|
|
|
|
|
|
|
|
def back(self):
|
2005-11-07 06:22:02 +08:00
|
|
|
"Undoes the last microparser. Use this for lookahead and backtracking."
|
2005-11-04 12:59:46 +08:00
|
|
|
if not len(self.backout):
|
2007-12-23 03:16:39 +08:00
|
|
|
raise TemplateSyntaxError("back called without some previous parsing")
|
2005-11-04 12:59:46 +08:00
|
|
|
self.pointer = self.backout.pop()
|
|
|
|
|
|
|
|
def tag(self):
|
2005-11-07 06:22:02 +08:00
|
|
|
"A microparser that just returns the next tag from the line."
|
2005-11-04 12:59:46 +08:00
|
|
|
subject = self.subject
|
|
|
|
i = self.pointer
|
|
|
|
if i >= len(subject):
|
2007-12-23 03:16:39 +08:00
|
|
|
raise TemplateSyntaxError("expected another tag, found end of string: %s" % subject)
|
2005-11-04 12:59:46 +08:00
|
|
|
p = i
|
|
|
|
while i < len(subject) and subject[i] not in (' ', '\t'):
|
|
|
|
i += 1
|
|
|
|
s = subject[p:i]
|
|
|
|
while i < len(subject) and subject[i] in (' ', '\t'):
|
|
|
|
i += 1
|
|
|
|
self.backout.append(self.pointer)
|
|
|
|
self.pointer = i
|
|
|
|
return s
|
|
|
|
|
|
|
|
def value(self):
|
2005-11-07 06:22:02 +08:00
|
|
|
"A microparser that parses for a value: some string constant or variable name."
|
2005-11-04 12:59:46 +08:00
|
|
|
subject = self.subject
|
|
|
|
i = self.pointer
|
|
|
|
if i >= len(subject):
|
2007-12-23 03:16:39 +08:00
|
|
|
raise TemplateSyntaxError("Searching for value. Expected another value but found end of string: %s" % subject)
|
2005-11-04 12:59:46 +08:00
|
|
|
if subject[i] in ('"', "'"):
|
|
|
|
p = i
|
|
|
|
i += 1
|
|
|
|
while i < len(subject) and subject[i] != subject[p]:
|
|
|
|
i += 1
|
|
|
|
if i >= len(subject):
|
2007-12-23 03:16:39 +08:00
|
|
|
raise TemplateSyntaxError("Searching for value. Unexpected end of string in column %d: %s" % (i, subject))
|
2005-11-04 12:59:46 +08:00
|
|
|
i += 1
|
|
|
|
res = subject[p:i]
|
|
|
|
while i < len(subject) and subject[i] in (' ', '\t'):
|
|
|
|
i += 1
|
|
|
|
self.backout.append(self.pointer)
|
|
|
|
self.pointer = i
|
|
|
|
return res
|
|
|
|
else:
|
|
|
|
p = i
|
|
|
|
while i < len(subject) and subject[i] not in (' ', '\t'):
|
2005-11-13 05:45:01 +08:00
|
|
|
if subject[i] in ('"', "'"):
|
|
|
|
c = subject[i]
|
|
|
|
i += 1
|
|
|
|
while i < len(subject) and subject[i] != c:
|
|
|
|
i += 1
|
|
|
|
if i >= len(subject):
|
2007-12-23 03:16:39 +08:00
|
|
|
raise TemplateSyntaxError("Searching for value. Unexpected end of string in column %d: %s" % (i, subject))
|
2005-11-04 12:59:46 +08:00
|
|
|
i += 1
|
|
|
|
s = subject[p:i]
|
|
|
|
while i < len(subject) and subject[i] in (' ', '\t'):
|
|
|
|
i += 1
|
|
|
|
self.backout.append(self.pointer)
|
|
|
|
self.pointer = i
|
|
|
|
return s
|
|
|
|
|
2005-11-24 07:10:17 +08:00
|
|
|
filter_raw_string = r"""
|
|
|
|
^%(i18n_open)s"(?P<i18n_constant>%(str)s)"%(i18n_close)s|
|
|
|
|
^"(?P<constant>%(str)s)"|
|
|
|
|
^(?P<var>[%(var_chars)s]+)|
|
|
|
|
(?:%(filter_sep)s
|
|
|
|
(?P<filter_name>\w+)
|
|
|
|
(?:%(arg_sep)s
|
|
|
|
(?:
|
|
|
|
%(i18n_open)s"(?P<i18n_arg>%(str)s)"%(i18n_close)s|
|
2005-11-27 06:46:31 +08:00
|
|
|
"(?P<constant_arg>%(str)s)"|
|
|
|
|
(?P<var_arg>[%(var_chars)s]+)
|
2005-11-24 07:10:17 +08:00
|
|
|
)
|
|
|
|
)?
|
|
|
|
)""" % {
|
|
|
|
'str': r"""[^"\\]*(?:\\.[^"\\]*)*""",
|
2007-07-08 02:24:27 +08:00
|
|
|
'var_chars': "\w\." ,
|
2005-11-24 07:10:17 +08:00
|
|
|
'filter_sep': re.escape(FILTER_SEPARATOR),
|
|
|
|
'arg_sep': re.escape(FILTER_ARGUMENT_SEPARATOR),
|
|
|
|
'i18n_open' : re.escape("_("),
|
|
|
|
'i18n_close' : re.escape(")"),
|
|
|
|
}
|
|
|
|
|
|
|
|
filter_raw_string = filter_raw_string.replace("\n", "").replace(" ", "")
|
2007-07-08 02:24:27 +08:00
|
|
|
filter_re = re.compile(filter_raw_string, re.UNICODE)
|
2005-11-24 07:10:17 +08:00
|
|
|
|
2005-11-27 06:46:31 +08:00
|
|
|
class FilterExpression(object):
|
2005-11-07 06:22:02 +08:00
|
|
|
"""
|
|
|
|
Parses a variable token and its optional filters (all as a single string),
|
|
|
|
and return a list of tuples of the filter name and arguments.
|
|
|
|
Sample:
|
|
|
|
>>> token = 'variable|default:"Default value"|date:"Y-m-d"'
|
2007-09-15 16:29:56 +08:00
|
|
|
>>> p = Parser('')
|
|
|
|
>>> fe = FilterExpression(token, p)
|
|
|
|
>>> len(fe.filters)
|
|
|
|
2
|
|
|
|
>>> fe.var
|
2005-11-07 06:22:02 +08:00
|
|
|
'variable'
|
|
|
|
|
|
|
|
This class should never be instantiated outside of the
|
|
|
|
get_filters_from_token helper function.
|
2005-07-13 09:25:57 +08:00
|
|
|
"""
|
2005-11-27 06:46:31 +08:00
|
|
|
def __init__(self, token, parser):
|
|
|
|
self.token = token
|
2005-11-24 07:10:17 +08:00
|
|
|
matches = filter_re.finditer(token)
|
|
|
|
var = None
|
|
|
|
filters = []
|
|
|
|
upto = 0
|
|
|
|
for match in matches:
|
|
|
|
start = match.start()
|
|
|
|
if upto != start:
|
2007-12-23 03:16:39 +08:00
|
|
|
raise TemplateSyntaxError("Could not parse some characters: %s|%s|%s" % \
|
|
|
|
(token[:upto], token[upto:start], token[start:]))
|
2005-11-24 07:10:17 +08:00
|
|
|
if var == None:
|
|
|
|
var, constant, i18n_constant = match.group("var", "constant", "i18n_constant")
|
|
|
|
if i18n_constant:
|
2007-11-29 05:04:05 +08:00
|
|
|
var = '"%s"' % _(i18n_constant.replace(r'\"', '"'))
|
2005-11-24 07:10:17 +08:00
|
|
|
elif constant:
|
2007-11-29 05:04:05 +08:00
|
|
|
var = '"%s"' % constant.replace(r'\"', '"')
|
2005-11-24 07:10:17 +08:00
|
|
|
upto = match.end()
|
|
|
|
if var == None:
|
2007-12-23 03:16:39 +08:00
|
|
|
raise TemplateSyntaxError("Could not find variable at start of %s" % token)
|
2005-11-24 07:10:17 +08:00
|
|
|
elif var.find(VARIABLE_ATTRIBUTE_SEPARATOR + '_') > -1 or var[0] == '_':
|
2007-12-23 03:16:39 +08:00
|
|
|
raise TemplateSyntaxError("Variables and attributes may not begin with underscores: '%s'" % var)
|
2005-11-24 07:10:17 +08:00
|
|
|
else:
|
|
|
|
filter_name = match.group("filter_name")
|
2005-11-27 06:46:31 +08:00
|
|
|
args = []
|
|
|
|
constant_arg, i18n_arg, var_arg = match.group("constant_arg", "i18n_arg", "var_arg")
|
2005-11-24 07:10:17 +08:00
|
|
|
if i18n_arg:
|
2006-05-02 09:31:56 +08:00
|
|
|
args.append((False, _(i18n_arg.replace(r'\"', '"'))))
|
2006-09-26 15:26:07 +08:00
|
|
|
elif constant_arg is not None:
|
2006-05-02 09:31:56 +08:00
|
|
|
args.append((False, constant_arg.replace(r'\"', '"')))
|
2005-11-27 06:46:31 +08:00
|
|
|
elif var_arg:
|
2007-09-21 12:00:32 +08:00
|
|
|
args.append((True, Variable(var_arg)))
|
2005-11-27 06:46:31 +08:00
|
|
|
filter_func = parser.find_filter(filter_name)
|
|
|
|
self.args_check(filter_name,filter_func, args)
|
|
|
|
filters.append( (filter_func,args))
|
2005-11-24 07:10:17 +08:00
|
|
|
upto = match.end()
|
|
|
|
if upto != len(token):
|
2007-12-23 03:16:39 +08:00
|
|
|
raise TemplateSyntaxError("Could not parse the remainder: '%s' from '%s'" % (token[upto:], token))
|
2007-09-21 12:00:32 +08:00
|
|
|
self.filters = filters
|
|
|
|
self.var = Variable(var)
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2006-07-04 11:21:44 +08:00
|
|
|
def resolve(self, context, ignore_failures=False):
|
2005-11-27 06:46:31 +08:00
|
|
|
try:
|
2007-09-21 12:00:32 +08:00
|
|
|
obj = self.var.resolve(context)
|
2005-11-27 06:46:31 +08:00
|
|
|
except VariableDoesNotExist:
|
2006-07-04 11:21:44 +08:00
|
|
|
if ignore_failures:
|
2006-09-04 22:02:11 +08:00
|
|
|
obj = None
|
2006-07-04 11:21:44 +08:00
|
|
|
else:
|
2006-09-04 22:02:11 +08:00
|
|
|
if settings.TEMPLATE_STRING_IF_INVALID:
|
2007-05-08 11:36:16 +08:00
|
|
|
global invalid_var_format_string
|
|
|
|
if invalid_var_format_string is None:
|
|
|
|
invalid_var_format_string = '%s' in settings.TEMPLATE_STRING_IF_INVALID
|
|
|
|
if invalid_var_format_string:
|
|
|
|
return settings.TEMPLATE_STRING_IF_INVALID % self.var
|
2006-09-04 22:02:11 +08:00
|
|
|
return settings.TEMPLATE_STRING_IF_INVALID
|
|
|
|
else:
|
|
|
|
obj = settings.TEMPLATE_STRING_IF_INVALID
|
2005-11-27 06:46:31 +08:00
|
|
|
for func, args in self.filters:
|
|
|
|
arg_vals = []
|
|
|
|
for lookup, arg in args:
|
|
|
|
if not lookup:
|
2007-11-17 20:11:26 +08:00
|
|
|
arg_vals.append(mark_safe(arg))
|
2005-11-27 06:46:31 +08:00
|
|
|
else:
|
2007-09-21 12:00:32 +08:00
|
|
|
arg_vals.append(arg.resolve(context))
|
2007-11-14 20:58:53 +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)
|
|
|
|
elif isinstance(obj, EscapeData):
|
|
|
|
obj = mark_for_escaping(new_obj)
|
|
|
|
else:
|
|
|
|
obj = new_obj
|
2005-11-27 06:46:31 +08:00
|
|
|
return obj
|
|
|
|
|
|
|
|
def args_check(name, func, provided):
|
|
|
|
provided = list(provided)
|
|
|
|
plen = len(provided)
|
2007-02-24 02:02:51 +08:00
|
|
|
# Check to see if a decorator is providing the real function.
|
|
|
|
func = getattr(func, '_decorated_function', func)
|
2006-06-08 12:29:10 +08:00
|
|
|
args, varargs, varkw, defaults = getargspec(func)
|
2005-11-27 06:46:31 +08:00
|
|
|
# First argument is filter input.
|
|
|
|
args.pop(0)
|
|
|
|
if defaults:
|
|
|
|
nondefs = args[:-len(defaults)]
|
|
|
|
else:
|
|
|
|
nondefs = args
|
|
|
|
# Args without defaults must be provided.
|
|
|
|
try:
|
|
|
|
for arg in nondefs:
|
|
|
|
provided.pop(0)
|
|
|
|
except IndexError:
|
|
|
|
# Not enough
|
2007-12-23 03:16:39 +08:00
|
|
|
raise TemplateSyntaxError("%s requires %d arguments, %d provided" % (name, len(nondefs), plen))
|
2005-11-27 06:46:31 +08:00
|
|
|
|
|
|
|
# Defaults can be overridden.
|
|
|
|
defaults = defaults and list(defaults) or []
|
|
|
|
try:
|
|
|
|
for parg in provided:
|
|
|
|
defaults.pop(0)
|
|
|
|
except IndexError:
|
|
|
|
# Too many.
|
2007-12-23 03:16:39 +08:00
|
|
|
raise TemplateSyntaxError("%s requires %d arguments, %d provided" % (name, len(nondefs), plen))
|
2005-11-27 06:46:31 +08:00
|
|
|
|
|
|
|
return True
|
|
|
|
args_check = staticmethod(args_check)
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return self.token
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
def resolve_variable(path, context):
|
|
|
|
"""
|
|
|
|
Returns the resolved variable, which may contain attribute syntax, within
|
2007-09-21 12:00:32 +08:00
|
|
|
the given context.
|
2007-11-14 20:58:53 +08:00
|
|
|
|
2007-09-21 12:00:32 +08:00
|
|
|
Deprecated; use the Variable class instead.
|
|
|
|
"""
|
|
|
|
return Variable(path).resolve(context)
|
|
|
|
|
|
|
|
class Variable(object):
|
|
|
|
"""
|
|
|
|
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
|
|
|
|
marks)::
|
2007-11-14 20:58:53 +08:00
|
|
|
|
2007-09-21 12:00:32 +08:00
|
|
|
>>> c = {'article': {'section':'News'}}
|
|
|
|
>>> Variable('article.section').resolve(c)
|
|
|
|
u'News'
|
|
|
|
>>> Variable('article').resolve(c)
|
|
|
|
{'section': 'News'}
|
|
|
|
>>> class AClass: pass
|
|
|
|
>>> c = AClass()
|
|
|
|
>>> c.article = AClass()
|
|
|
|
>>> c.article.section = 'News'
|
|
|
|
>>> Variable('article.section').resolve(c)
|
|
|
|
u'News'
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
(The example assumes VARIABLE_ATTRIBUTE_SEPARATOR is '.')
|
|
|
|
"""
|
2007-11-14 20:58:53 +08:00
|
|
|
|
2007-09-21 12:00:32 +08:00
|
|
|
def __init__(self, var):
|
|
|
|
self.var = var
|
|
|
|
self.literal = None
|
|
|
|
self.lookups = None
|
2007-11-17 12:04:12 +08:00
|
|
|
self.translate = False
|
2007-11-14 20:58:53 +08:00
|
|
|
|
2007-09-21 12:00:32 +08:00
|
|
|
try:
|
|
|
|
# First try to treat this variable as a number.
|
|
|
|
#
|
2007-11-14 20:58:53 +08:00
|
|
|
# Note that this could cause an OverflowError here that we're not
|
2007-09-21 12:00:32 +08:00
|
|
|
# catching. Since this should only happen at compile time, that's
|
|
|
|
# probably OK.
|
|
|
|
self.literal = float(var)
|
2007-11-14 20:58:53 +08:00
|
|
|
|
2007-09-21 12:00:32 +08:00
|
|
|
# So it's a float... is it an int? If the original value contained a
|
|
|
|
# dot or an "e" then it was a float, not an int.
|
|
|
|
if '.' not in var and 'e' not in var.lower():
|
|
|
|
self.literal = int(self.literal)
|
2007-11-14 20:58:53 +08:00
|
|
|
|
2007-09-21 12:00:32 +08:00
|
|
|
# "2." is invalid
|
|
|
|
if var.endswith('.'):
|
|
|
|
raise ValueError
|
|
|
|
|
|
|
|
except ValueError:
|
|
|
|
# A ValueError means that the variable isn't a number.
|
2007-11-17 12:04:12 +08:00
|
|
|
if var.startswith('_(') and var.endswith(')'):
|
|
|
|
# The result of the lookup should be translated at rendering
|
|
|
|
# time.
|
|
|
|
self.translate = True
|
|
|
|
var = var[2:-1]
|
2007-09-21 12:00:32 +08:00
|
|
|
# If it's wrapped with quotes (single or double), then
|
|
|
|
# we're also dealing with a literal.
|
|
|
|
if var[0] in "\"'" and var[0] == var[-1]:
|
2007-11-17 20:11:26 +08:00
|
|
|
self.literal = mark_safe(var[1:-1])
|
2007-09-21 12:00:32 +08:00
|
|
|
else:
|
|
|
|
# Otherwise we'll set self.lookups so that resolve() knows we're
|
|
|
|
# dealing with a bonafide variable
|
|
|
|
self.lookups = tuple(var.split(VARIABLE_ATTRIBUTE_SEPARATOR))
|
2007-11-14 20:58:53 +08:00
|
|
|
|
2007-09-21 12:00:32 +08:00
|
|
|
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
|
2007-11-17 12:04:12 +08:00
|
|
|
value = self._resolve_lookup(context)
|
2007-09-21 12:00:32 +08:00
|
|
|
else:
|
|
|
|
# We're dealing with a literal, so it's already been "resolved"
|
2007-11-17 12:04:12 +08:00
|
|
|
value = self.literal
|
|
|
|
if self.translate:
|
|
|
|
return _(value)
|
|
|
|
return value
|
2007-11-14 20:58:53 +08:00
|
|
|
|
2007-09-21 12:00:32 +08:00
|
|
|
def __repr__(self):
|
|
|
|
return "<%s: %r>" % (self.__class__.__name__, self.var)
|
2007-11-14 20:58:53 +08:00
|
|
|
|
2007-09-21 12:00:32 +08:00
|
|
|
def __str__(self):
|
|
|
|
return self.var
|
|
|
|
|
|
|
|
def _resolve_lookup(self, context):
|
|
|
|
"""
|
|
|
|
Performs resolution of a real variable (i.e. not a literal) against the
|
2007-11-14 20:58:53 +08:00
|
|
|
given context.
|
|
|
|
|
2007-09-21 12:00:32 +08:00
|
|
|
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.
|
|
|
|
"""
|
2005-09-01 10:18:04 +08:00
|
|
|
current = context
|
2007-09-21 12:00:32 +08:00
|
|
|
for bit in self.lookups:
|
2005-09-01 10:18:04 +08:00
|
|
|
try: # dictionary lookup
|
2007-09-21 12:00:32 +08:00
|
|
|
current = current[bit]
|
2005-09-01 10:18:04 +08:00
|
|
|
except (TypeError, AttributeError, KeyError):
|
|
|
|
try: # attribute lookup
|
2007-09-21 12:00:32 +08:00
|
|
|
current = getattr(current, bit)
|
2005-09-01 10:18:04 +08:00
|
|
|
if callable(current):
|
|
|
|
if getattr(current, 'alters_data', False):
|
2006-05-02 09:31:56 +08:00
|
|
|
current = settings.TEMPLATE_STRING_IF_INVALID
|
2005-09-01 10:18:04 +08:00
|
|
|
else:
|
|
|
|
try: # method call (assuming no args required)
|
|
|
|
current = current()
|
|
|
|
except TypeError: # arguments *were* required
|
2005-11-29 13:53:05 +08:00
|
|
|
# GOTCHA: This will also catch any TypeError
|
|
|
|
# raised in the function itself.
|
2006-05-02 09:31:56 +08:00
|
|
|
current = settings.TEMPLATE_STRING_IF_INVALID # invalid method call
|
|
|
|
except Exception, e:
|
|
|
|
if getattr(e, 'silent_variable_failure', False):
|
|
|
|
current = settings.TEMPLATE_STRING_IF_INVALID
|
|
|
|
else:
|
|
|
|
raise
|
2005-09-01 10:18:04 +08:00
|
|
|
except (TypeError, AttributeError):
|
|
|
|
try: # list-index lookup
|
2007-09-21 12:00:32 +08:00
|
|
|
current = current[int(bit)]
|
2007-02-28 04:25:27 +08:00
|
|
|
except (IndexError, # list index out of range
|
|
|
|
ValueError, # invalid literal for int()
|
2007-09-21 12:00:32 +08:00
|
|
|
KeyError, # current is a dict without `int(bit)` key
|
2007-02-28 04:25:27 +08:00
|
|
|
TypeError, # unsubscriptable object
|
|
|
|
):
|
2007-09-21 12:00:32 +08:00
|
|
|
raise VariableDoesNotExist("Failed lookup for key [%s] in %r", (bit, current)) # missing attribute
|
2006-05-02 09:31:56 +08:00
|
|
|
except Exception, e:
|
|
|
|
if getattr(e, 'silent_variable_failure', False):
|
|
|
|
current = settings.TEMPLATE_STRING_IF_INVALID
|
|
|
|
else:
|
2006-06-07 12:12:39 +08:00
|
|
|
raise
|
2007-11-14 20:58:53 +08:00
|
|
|
|
2007-09-21 12:00:32 +08:00
|
|
|
return current
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2006-06-08 13:00:13 +08:00
|
|
|
class Node(object):
|
2008-02-04 12:52:37 +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
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
def render(self, context):
|
|
|
|
"Return the node rendered as a string"
|
2007-06-22 15:15:04 +08:00
|
|
|
pass
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
yield self
|
|
|
|
|
|
|
|
def get_nodes_by_type(self, nodetype):
|
|
|
|
"Return a list of all nodes (within this node and its nodelist) of the given type"
|
|
|
|
nodes = []
|
|
|
|
if isinstance(self, nodetype):
|
|
|
|
nodes.append(self)
|
|
|
|
if hasattr(self, 'nodelist'):
|
|
|
|
nodes.extend(self.nodelist.get_nodes_by_type(nodetype))
|
|
|
|
return nodes
|
|
|
|
|
|
|
|
class NodeList(list):
|
2008-02-06 07:41:48 +08:00
|
|
|
# Set to True the first time a non-TextNode is inserted by
|
|
|
|
# extend_nodelist().
|
|
|
|
contains_nontext = False
|
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
def render(self, context):
|
2007-06-22 15:15:04 +08:00
|
|
|
bits = []
|
2005-07-13 09:25:57 +08:00
|
|
|
for node in self:
|
2007-06-22 15:15:04 +08:00
|
|
|
if isinstance(node, Node):
|
|
|
|
bits.append(self.render_node(node, context))
|
|
|
|
else:
|
|
|
|
bits.append(node)
|
2007-11-30 23:32:01 +08:00
|
|
|
return mark_safe(''.join([force_unicode(b) for b in bits]))
|
2005-07-13 09:25:57 +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
|
|
|
|
|
2007-06-22 15:15:04 +08:00
|
|
|
def render_node(self, node, context):
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
return node.render(context)
|
2007-06-22 15:15:04 +08:00
|
|
|
|
2005-07-13 09:25:57 +08:00
|
|
|
class TextNode(Node):
|
|
|
|
def __init__(self, s):
|
|
|
|
self.s = s
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return "<Text Node: '%s'>" % self.s[:25]
|
|
|
|
|
|
|
|
def render(self, context):
|
|
|
|
return self.s
|
|
|
|
|
|
|
|
class VariableNode(Node):
|
2005-11-27 06:46:31 +08:00
|
|
|
def __init__(self, filter_expression):
|
|
|
|
self.filter_expression = filter_expression
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
def __repr__(self):
|
2005-11-27 06:46:31 +08:00
|
|
|
return "<Variable Node: %s>" % self.filter_expression
|
2005-07-13 09:25:57 +08:00
|
|
|
|
2005-11-24 07:10:17 +08:00
|
|
|
def render(self, context):
|
2007-11-14 20:58:53 +08:00
|
|
|
try:
|
|
|
|
output = force_unicode(self.filter_expression.resolve(context))
|
|
|
|
except UnicodeDecodeError:
|
|
|
|
# Unicode conversion can fail sometimes for reasons out of our
|
|
|
|
# control (e.g. exception rendering). In that case, we fail quietly.
|
|
|
|
return ''
|
|
|
|
if (context.autoescape and not isinstance(output, SafeData)) or isinstance(output, EscapeData):
|
|
|
|
return force_unicode(escape(output))
|
|
|
|
else:
|
|
|
|
return force_unicode(output)
|
2005-11-24 07:10:17 +08:00
|
|
|
|
2005-11-27 06:46:31 +08:00
|
|
|
def generic_tag_compiler(params, defaults, name, node_class, parser, token):
|
|
|
|
"Returns a template.Node subclass."
|
2006-07-10 18:48:08 +08:00
|
|
|
bits = token.split_contents()[1:]
|
2005-11-27 06:46:31 +08:00
|
|
|
bmax = len(params)
|
|
|
|
def_len = defaults and len(defaults) or 0
|
|
|
|
bmin = bmax - def_len
|
|
|
|
if(len(bits) < bmin or len(bits) > bmax):
|
|
|
|
if bmin == bmax:
|
|
|
|
message = "%s takes %s arguments" % (name, bmin)
|
|
|
|
else:
|
|
|
|
message = "%s takes between %s and %s arguments" % (name, bmin, bmax)
|
2007-12-23 03:16:39 +08:00
|
|
|
raise TemplateSyntaxError(message)
|
2005-11-27 06:46:31 +08:00
|
|
|
return node_class(bits)
|
|
|
|
|
|
|
|
class Library(object):
|
|
|
|
def __init__(self):
|
|
|
|
self.filters = {}
|
|
|
|
self.tags = {}
|
|
|
|
|
2005-11-30 08:08:56 +08:00
|
|
|
def tag(self, name=None, compile_function=None):
|
2005-11-27 06:46:31 +08:00
|
|
|
if name == None and compile_function == None:
|
|
|
|
# @register.tag()
|
|
|
|
return self.tag_function
|
|
|
|
elif name != None and compile_function == None:
|
|
|
|
if(callable(name)):
|
|
|
|
# @register.tag
|
|
|
|
return self.tag_function(name)
|
|
|
|
else:
|
|
|
|
# @register.tag('somename') or @register.tag(name='somename')
|
|
|
|
def dec(func):
|
|
|
|
return self.tag(name, func)
|
|
|
|
return dec
|
|
|
|
elif name != None and compile_function != None:
|
|
|
|
# register.tag('somename', somefunc)
|
|
|
|
self.tags[name] = compile_function
|
|
|
|
return compile_function
|
|
|
|
else:
|
2007-12-23 03:16:39 +08:00
|
|
|
raise InvalidTemplateLibrary("Unsupported arguments to Library.tag: (%r, %r)", (name, compile_function))
|
2005-11-27 06:46:31 +08:00
|
|
|
|
|
|
|
def tag_function(self,func):
|
2007-02-24 07:05:16 +08:00
|
|
|
self.tags[getattr(func, "_decorated_function", func).__name__] = func
|
2005-11-27 06:46:31 +08:00
|
|
|
return func
|
|
|
|
|
2005-11-30 08:08:56 +08:00
|
|
|
def filter(self, name=None, filter_func=None):
|
2005-11-27 06:46:31 +08:00
|
|
|
if name == None and filter_func == None:
|
|
|
|
# @register.filter()
|
|
|
|
return self.filter_function
|
|
|
|
elif filter_func == None:
|
|
|
|
if(callable(name)):
|
|
|
|
# @register.filter
|
|
|
|
return self.filter_function(name)
|
|
|
|
else:
|
|
|
|
# @register.filter('somename') or @register.filter(name='somename')
|
|
|
|
def dec(func):
|
|
|
|
return self.filter(name, func)
|
|
|
|
return dec
|
|
|
|
elif name != None and filter_func != None:
|
|
|
|
# register.filter('somename', somefunc)
|
|
|
|
self.filters[name] = filter_func
|
2005-11-30 08:08:56 +08:00
|
|
|
return filter_func
|
2005-11-27 06:46:31 +08:00
|
|
|
else:
|
2007-12-23 03:16:39 +08:00
|
|
|
raise InvalidTemplateLibrary("Unsupported arguments to Library.filter: (%r, %r)", (name, filter_func))
|
2005-11-27 06:46:31 +08:00
|
|
|
|
|
|
|
def filter_function(self, func):
|
2007-02-24 07:05:16 +08:00
|
|
|
self.filters[getattr(func, "_decorated_function", func).__name__] = func
|
2005-11-27 06:46:31 +08:00
|
|
|
return func
|
|
|
|
|
|
|
|
def simple_tag(self,func):
|
2006-06-08 12:29:10 +08:00
|
|
|
params, xx, xxx, defaults = getargspec(func)
|
2005-11-27 06:46:31 +08:00
|
|
|
|
|
|
|
class SimpleNode(Node):
|
|
|
|
def __init__(self, vars_to_resolve):
|
2007-09-21 12:00:32 +08:00
|
|
|
self.vars_to_resolve = map(Variable, vars_to_resolve)
|
2005-11-27 06:46:31 +08:00
|
|
|
|
|
|
|
def render(self, context):
|
2007-09-21 12:00:32 +08:00
|
|
|
resolved_vars = [var.resolve(context) for var in self.vars_to_resolve]
|
2005-11-27 06:46:31 +08:00
|
|
|
return func(*resolved_vars)
|
|
|
|
|
2007-02-24 07:05:16 +08:00
|
|
|
compile_func = curry(generic_tag_compiler, params, defaults, getattr(func, "_decorated_function", func).__name__, SimpleNode)
|
2005-11-27 06:46:31 +08:00
|
|
|
compile_func.__doc__ = func.__doc__
|
2007-02-24 07:05:16 +08:00
|
|
|
self.tag(getattr(func, "_decorated_function", func).__name__, compile_func)
|
2005-11-27 06:46:31 +08:00
|
|
|
return func
|
|
|
|
|
|
|
|
def inclusion_tag(self, file_name, context_class=Context, takes_context=False):
|
|
|
|
def dec(func):
|
2006-06-08 12:29:10 +08:00
|
|
|
params, xx, xxx, defaults = getargspec(func)
|
2005-11-27 06:46:31 +08:00
|
|
|
if takes_context:
|
|
|
|
if params[0] == 'context':
|
|
|
|
params = params[1:]
|
|
|
|
else:
|
2007-12-23 03:16:39 +08:00
|
|
|
raise TemplateSyntaxError("Any tag function decorated with takes_context=True must have a first argument of 'context'")
|
2005-11-27 06:46:31 +08:00
|
|
|
|
|
|
|
class InclusionNode(Node):
|
|
|
|
def __init__(self, vars_to_resolve):
|
2007-09-21 12:00:32 +08:00
|
|
|
self.vars_to_resolve = map(Variable, vars_to_resolve)
|
2005-11-27 06:46:31 +08:00
|
|
|
|
2007-06-22 15:15:04 +08:00
|
|
|
def render(self, context):
|
2007-09-21 12:00:32 +08:00
|
|
|
resolved_vars = [var.resolve(context) for var in self.vars_to_resolve]
|
2005-11-27 06:46:31 +08:00
|
|
|
if takes_context:
|
|
|
|
args = [context] + resolved_vars
|
|
|
|
else:
|
|
|
|
args = resolved_vars
|
|
|
|
|
|
|
|
dict = func(*args)
|
|
|
|
|
|
|
|
if not getattr(self, 'nodelist', False):
|
2006-11-07 12:13:06 +08:00
|
|
|
from django.template.loader import get_template, select_template
|
2007-09-15 03:55:24 +08:00
|
|
|
if not isinstance(file_name, basestring) and is_iterable(file_name):
|
2006-11-07 12:13:06 +08:00
|
|
|
t = select_template(file_name)
|
|
|
|
else:
|
|
|
|
t = get_template(file_name)
|
2005-11-27 06:46:31 +08:00
|
|
|
self.nodelist = t.nodelist
|
2007-11-14 20:58:53 +08:00
|
|
|
return self.nodelist.render(context_class(dict,
|
|
|
|
autoescape=context.autoescape))
|
2005-11-27 06:46:31 +08:00
|
|
|
|
2007-02-24 07:05:16 +08:00
|
|
|
compile_func = curry(generic_tag_compiler, params, defaults, getattr(func, "_decorated_function", func).__name__, InclusionNode)
|
2005-11-27 06:46:31 +08:00
|
|
|
compile_func.__doc__ = func.__doc__
|
2007-02-24 07:05:16 +08:00
|
|
|
self.tag(getattr(func, "_decorated_function", func).__name__, compile_func)
|
2005-11-27 06:46:31 +08:00
|
|
|
return func
|
|
|
|
return dec
|
|
|
|
|
|
|
|
def get_library(module_name):
|
|
|
|
lib = libraries.get(module_name, None)
|
|
|
|
if not lib:
|
|
|
|
try:
|
2006-10-31 04:50:27 +08:00
|
|
|
mod = __import__(module_name, {}, {}, [''])
|
2005-11-27 06:46:31 +08:00
|
|
|
except ImportError, e:
|
2007-12-23 03:16:39 +08:00
|
|
|
raise InvalidTemplateLibrary("Could not load template library from %s, %s" % (module_name, e))
|
2005-11-28 00:43:56 +08:00
|
|
|
try:
|
|
|
|
lib = mod.register
|
|
|
|
libraries[module_name] = lib
|
|
|
|
except AttributeError:
|
2007-12-23 03:16:39 +08:00
|
|
|
raise InvalidTemplateLibrary("Template library %s does not have a variable named 'register'" % module_name)
|
2005-11-27 06:46:31 +08:00
|
|
|
return lib
|
|
|
|
|
|
|
|
def add_to_builtins(module_name):
|
|
|
|
builtins.append(get_library(module_name))
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
add_to_builtins('django.template.defaulttags')
|
|
|
|
add_to_builtins('django.template.defaultfilters')
|