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:
|
|
|
|
|
|
|
|
>>> import template
|
|
|
|
>>> s = '''
|
|
|
|
... <html>
|
|
|
|
... {% if test %}
|
|
|
|
... <h1>{{ varvalue }}</h1>
|
|
|
|
... {% endif %}
|
|
|
|
... </html>
|
|
|
|
... '''
|
|
|
|
>>> 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)
|
|
|
|
'\n<html>\n\n <h1>Hello</h1>\n\n</html>\n'
|
|
|
|
>>> c = template.Context({'test':False, 'varvalue': 'Hello'})
|
|
|
|
>>> t.render(c)
|
|
|
|
'\n<html>\n\n</html>\n'
|
|
|
|
"""
|
|
|
|
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
|
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 _
|
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)))
|
2007-03-09 14:12:15 +08:00
|
|
|
# matches if the string is valid number
|
|
|
|
number_re = re.compile(r'[-+]?(\d+|\d*\.\d+)$')
|
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):
|
2007-02-10 06:01:13 +08:00
|
|
|
return self.msg % 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>'):
|
2005-07-13 09:25:57 +08:00
|
|
|
"Compilation stage"
|
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.")
|
2006-05-02 09:31:56 +08:00
|
|
|
if settings.TEMPLATE_DEBUG and origin == None:
|
2005-11-24 07:10:17 +08:00
|
|
|
origin = StringOrigin(template_string)
|
|
|
|
# Could do some crazy stack-frame stuff to record where this string
|
|
|
|
# came from...
|
|
|
|
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"
|
2005-11-24 07:10:17 +08:00
|
|
|
lexer = lexer_factory(template_string, origin)
|
|
|
|
parser = parser_factory(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):
|
2006-10-25 05:30:38 +08:00
|
|
|
"The 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):
|
|
|
|
"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 DebugLexer(Lexer):
|
|
|
|
def __init__(self, template_string, origin):
|
|
|
|
super(DebugLexer, self).__init__(template_string, origin)
|
|
|
|
|
|
|
|
def tokenize(self):
|
|
|
|
"Return a list of tokens from a given template_string"
|
2007-04-27 20:16:22 +08:00
|
|
|
result, upto = [], 0
|
2005-11-24 07:10:17 +08:00
|
|
|
for match in tag_re.finditer(self.template_string):
|
|
|
|
start, end = match.span()
|
|
|
|
if start > upto:
|
2007-04-27 20:16:22 +08:00
|
|
|
result.append(self.create_token(self.template_string[upto:start], (upto, start), False))
|
2005-11-24 07:10:17 +08:00
|
|
|
upto = start
|
2007-04-27 20:16:22 +08:00
|
|
|
result.append(self.create_token(self.template_string[start:end], (start, end), True))
|
2005-11-24 07:10:17 +08:00
|
|
|
upto = end
|
|
|
|
last_bit = self.template_string[upto:]
|
|
|
|
if last_bit:
|
2007-04-27 20:16:22 +08:00
|
|
|
result.append(self.create_token(last_bit, (upto, upto + len(last_bit)), False))
|
|
|
|
return result
|
2005-11-24 07:10:17 +08:00
|
|
|
|
2007-04-27 20:16:22 +08:00
|
|
|
def create_token(self, token_string, source, in_tag):
|
|
|
|
token = super(DebugLexer, self).create_token(token_string, in_tag)
|
2007-04-28 12:45:38 +08:00
|
|
|
token.source = self.origin, source
|
2005-11-24 07:10:17 +08:00
|
|
|
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):
|
|
|
|
nodelist.append(node)
|
|
|
|
|
|
|
|
def enter_command(self, command, token):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def exit_command(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def error(self, token, msg ):
|
|
|
|
return TemplateSyntaxError(msg)
|
|
|
|
|
|
|
|
def empty_variable(self, token):
|
|
|
|
raise self.error( token, "Empty variable tag")
|
|
|
|
|
|
|
|
def empty_block_tag(self, token):
|
|
|
|
raise self.error( token, "Empty block tag")
|
|
|
|
|
|
|
|
def invalid_block_tag(self, token, command):
|
|
|
|
raise self.error( token, "Invalid block tag: '%s'" % command)
|
|
|
|
|
|
|
|
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:
|
|
|
|
raise TemplateSyntaxError, "Invalid filter: '%s'" % filter_name
|
|
|
|
|
2005-11-24 07:10:17 +08:00
|
|
|
class DebugParser(Parser):
|
|
|
|
def __init__(self, lexer):
|
|
|
|
super(DebugParser, self).__init__(lexer)
|
|
|
|
self.command_stack = []
|
|
|
|
|
|
|
|
def enter_command(self, command, token):
|
|
|
|
self.command_stack.append( (command, token.source) )
|
|
|
|
|
|
|
|
def exit_command(self):
|
|
|
|
self.command_stack.pop()
|
|
|
|
|
|
|
|
def error(self, token, msg):
|
|
|
|
return self.source_error(token.source, msg)
|
|
|
|
|
|
|
|
def source_error(self, source,msg):
|
|
|
|
e = TemplateSyntaxError(msg)
|
|
|
|
e.source = source
|
|
|
|
return e
|
|
|
|
|
|
|
|
def create_nodelist(self):
|
|
|
|
return DebugNodeList()
|
|
|
|
|
|
|
|
def create_variable_node(self, contents):
|
|
|
|
return DebugVariableNode(contents)
|
|
|
|
|
|
|
|
def extend_nodelist(self, nodelist, node, token):
|
|
|
|
node.source = token.source
|
|
|
|
super(DebugParser, self).extend_nodelist(nodelist, node, token)
|
|
|
|
|
|
|
|
def unclosed_block_tag(self, parse_until):
|
2006-07-26 02:53:27 +08:00
|
|
|
command, source = self.command_stack.pop()
|
2005-11-24 07:10:17 +08:00
|
|
|
msg = "Unclosed tag '%s'. Looking for one of: %s " % (command, ', '.join(parse_until))
|
|
|
|
raise self.source_error( source, msg)
|
|
|
|
|
|
|
|
def compile_function_error(self, token, e):
|
|
|
|
if not hasattr(e, 'source'):
|
|
|
|
e.source = token.source
|
|
|
|
|
2006-05-02 09:31:56 +08:00
|
|
|
def lexer_factory(*args, **kwargs):
|
|
|
|
if settings.TEMPLATE_DEBUG:
|
|
|
|
return DebugLexer(*args, **kwargs)
|
|
|
|
else:
|
|
|
|
return Lexer(*args, **kwargs)
|
|
|
|
|
|
|
|
def parser_factory(*args, **kwargs):
|
|
|
|
if settings.TEMPLATE_DEBUG:
|
|
|
|
return DebugParser(*args, **kwargs)
|
|
|
|
else:
|
|
|
|
return Parser(*args, **kwargs)
|
|
|
|
|
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."
|
2005-11-04 12:59:46 +08:00
|
|
|
raise NotImplemented
|
|
|
|
|
|
|
|
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):
|
|
|
|
raise TemplateSyntaxError, "back called without some previous parsing"
|
|
|
|
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):
|
|
|
|
raise TemplateSyntaxError, "expected another tag, found end of string: %s" % subject
|
|
|
|
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):
|
2005-11-07 06:22:02 +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):
|
2006-09-05 08:19:50 +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-05-24 20:28:53 +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"'
|
|
|
|
>>> p = FilterParser(token)
|
|
|
|
>>> p.filters
|
|
|
|
[('default', 'Default value'), ('date', 'Y-m-d')]
|
|
|
|
>>> p.var
|
|
|
|
'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:
|
|
|
|
raise TemplateSyntaxError, "Could not parse some characters: %s|%s|%s" % \
|
|
|
|
(token[:upto], token[upto:start], token[start:])
|
|
|
|
if var == None:
|
|
|
|
var, constant, i18n_constant = match.group("var", "constant", "i18n_constant")
|
|
|
|
if i18n_constant:
|
|
|
|
var = '"%s"' % _(i18n_constant)
|
|
|
|
elif constant:
|
|
|
|
var = '"%s"' % constant
|
|
|
|
upto = match.end()
|
|
|
|
if var == None:
|
|
|
|
raise TemplateSyntaxError, "Could not find variable at start of %s" % token
|
|
|
|
elif var.find(VARIABLE_ATTRIBUTE_SEPARATOR + '_') > -1 or var[0] == '_':
|
|
|
|
raise TemplateSyntaxError, "Variables and attributes may not begin with underscores: '%s'" % var
|
|
|
|
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:
|
|
|
|
args.append((True, var_arg))
|
|
|
|
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-04-25 15:05:31 +08:00
|
|
|
raise TemplateSyntaxError, "Could not parse the remainder: '%s' from '%s'" % (token[upto:], token)
|
2006-06-07 12:12:39 +08:00
|
|
|
self.var, self.filters = var, filters
|
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:
|
|
|
|
obj = resolve_variable(self.var, context)
|
|
|
|
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:
|
|
|
|
arg_vals.append(arg)
|
|
|
|
else:
|
|
|
|
arg_vals.append(resolve_variable(arg, context))
|
|
|
|
obj = func(obj, *arg_vals)
|
|
|
|
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
|
|
|
|
raise TemplateSyntaxError, "%s requires %d arguments, %d provided" % (name, len(nondefs), plen)
|
|
|
|
|
|
|
|
# Defaults can be overridden.
|
|
|
|
defaults = defaults and list(defaults) or []
|
|
|
|
try:
|
|
|
|
for parg in provided:
|
|
|
|
defaults.pop(0)
|
|
|
|
except IndexError:
|
|
|
|
# Too many.
|
|
|
|
raise TemplateSyntaxError, "%s requires %d arguments, %d provided" % (name, len(nondefs), plen)
|
|
|
|
|
|
|
|
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
|
2005-09-01 10:18:04 +08:00
|
|
|
the given context. The variable may be a hard-coded string (if it begins
|
2006-05-02 09:31:56 +08:00
|
|
|
and ends with single or double quote marks).
|
2005-07-13 09:25:57 +08:00
|
|
|
|
|
|
|
>>> c = {'article': {'section':'News'}}
|
|
|
|
>>> resolve_variable('article.section', c)
|
|
|
|
'News'
|
|
|
|
>>> resolve_variable('article', c)
|
|
|
|
{'section': 'News'}
|
|
|
|
>>> class AClass: pass
|
|
|
|
>>> c = AClass()
|
|
|
|
>>> c.article = AClass()
|
|
|
|
>>> c.article.section = 'News'
|
|
|
|
>>> resolve_variable('article.section', c)
|
|
|
|
'News'
|
|
|
|
|
|
|
|
(The example assumes VARIABLE_ATTRIBUTE_SEPARATOR is '.')
|
|
|
|
"""
|
2007-03-09 14:12:15 +08:00
|
|
|
if number_re.match(path):
|
2005-12-16 13:33:24 +08:00
|
|
|
number_type = '.' in path and float or int
|
2007-03-09 14:12:15 +08:00
|
|
|
current = number_type(path)
|
2005-12-16 13:33:24 +08:00
|
|
|
elif path[0] in ('"', "'") and path[0] == path[-1]:
|
2005-09-01 10:18:04 +08:00
|
|
|
current = path[1:-1]
|
|
|
|
else:
|
|
|
|
current = context
|
|
|
|
bits = path.split(VARIABLE_ATTRIBUTE_SEPARATOR)
|
|
|
|
while bits:
|
|
|
|
try: # dictionary lookup
|
|
|
|
current = current[bits[0]]
|
|
|
|
except (TypeError, AttributeError, KeyError):
|
|
|
|
try: # attribute lookup
|
|
|
|
current = getattr(current, bits[0])
|
|
|
|
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
|
|
|
|
current = current[int(bits[0])]
|
2007-02-28 04:25:27 +08:00
|
|
|
except (IndexError, # list index out of range
|
|
|
|
ValueError, # invalid literal for int()
|
|
|
|
KeyError, # current is a dict without `int(bits[0])` key
|
|
|
|
TypeError, # unsubscriptable object
|
|
|
|
):
|
2007-02-06 21:59:24 +08:00
|
|
|
raise VariableDoesNotExist("Failed lookup for key [%s] in %r", (bits[0], 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
|
2005-09-01 10:18:04 +08:00
|
|
|
del bits[0]
|
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
|
|
|
if isinstance(current, (basestring, Promise)):
|
|
|
|
try:
|
|
|
|
current = force_unicode(current)
|
|
|
|
except UnicodeDecodeError:
|
|
|
|
# Failing to convert to unicode can happen sometimes (e.g. debug
|
|
|
|
# tracebacks). So we allow it in this particular instance.
|
|
|
|
pass
|
2005-07-13 09:25:57 +08:00
|
|
|
return current
|
|
|
|
|
2006-06-08 13:00:13 +08:00
|
|
|
class Node(object):
|
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):
|
|
|
|
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)
|
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 ''.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-11-24 07:10:17 +08:00
|
|
|
class DebugNodeList(NodeList):
|
2007-06-22 15:15:04 +08:00
|
|
|
def render_node(self, node, context):
|
|
|
|
try:
|
|
|
|
result = node.render(context)
|
|
|
|
except TemplateSyntaxError, e:
|
|
|
|
if not hasattr(e, 'source'):
|
|
|
|
e.source = node.source
|
|
|
|
raise
|
|
|
|
except Exception, e:
|
|
|
|
from sys import exc_info
|
|
|
|
wrapped = TemplateSyntaxError('Caught an exception while rendering: %s' % e)
|
|
|
|
wrapped.source = node.source
|
|
|
|
wrapped.exc_info = exc_info()
|
|
|
|
raise wrapped
|
|
|
|
return result
|
2005-11-24 07:10:17 +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):
|
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 self.filter_expression.resolve(context)
|
2005-11-24 07:10:17 +08:00
|
|
|
|
|
|
|
class DebugVariableNode(VariableNode):
|
|
|
|
def render(self, context):
|
|
|
|
try:
|
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 self.filter_expression.resolve(context)
|
2005-11-24 07:10:17 +08:00
|
|
|
except TemplateSyntaxError, e:
|
|
|
|
if not hasattr(e, 'source'):
|
|
|
|
e.source = self.source
|
|
|
|
raise
|
2005-07-13 09:25:57 +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)
|
|
|
|
raise TemplateSyntaxError, message
|
|
|
|
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:
|
|
|
|
raise InvalidTemplateLibrary, "Unsupported arguments to Library.tag: (%r, %r)", (name, compile_function)
|
|
|
|
|
|
|
|
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:
|
2006-07-22 04:39:17 +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):
|
|
|
|
self.vars_to_resolve = vars_to_resolve
|
|
|
|
|
|
|
|
def render(self, context):
|
|
|
|
resolved_vars = [resolve_variable(var, context) for var in self.vars_to_resolve]
|
|
|
|
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:
|
|
|
|
raise TemplateSyntaxError, "Any tag function decorated with takes_context=True must have a first argument of 'context'"
|
|
|
|
|
|
|
|
class InclusionNode(Node):
|
|
|
|
def __init__(self, vars_to_resolve):
|
|
|
|
self.vars_to_resolve = vars_to_resolve
|
|
|
|
|
2007-06-22 15:15:04 +08:00
|
|
|
def render(self, context):
|
2005-11-27 06:46:31 +08:00
|
|
|
resolved_vars = [resolve_variable(var, context) for var in self.vars_to_resolve]
|
|
|
|
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
|
|
|
|
if hasattr(file_name, '__iter__'):
|
|
|
|
t = select_template(file_name)
|
|
|
|
else:
|
|
|
|
t = get_template(file_name)
|
2005-11-27 06:46:31 +08:00
|
|
|
self.nodelist = t.nodelist
|
2007-06-22 15:15:04 +08:00
|
|
|
return self.nodelist.render(context_class(dict))
|
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:
|
|
|
|
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:
|
|
|
|
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')
|