PageRenderTime 26ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/python/lib/Lib/site-packages/django/template/defaulttags.py

http://github.com/JetBrains/intellij-community
Python | 1365 lines | 1314 code | 15 blank | 36 comment | 43 complexity | 394703b6a00af8e6ae7f146b58e3866b MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, MPL-2.0-no-copyleft-exception, MIT, EPL-1.0, AGPL-1.0
  1. """Default tags used by the template system, available to all templates."""
  2. import sys
  3. import re
  4. from itertools import groupby, cycle as itertools_cycle
  5. from django.template.base import Node, NodeList, Template, Context, Variable
  6. from django.template.base import TemplateSyntaxError, VariableDoesNotExist, BLOCK_TAG_START, BLOCK_TAG_END, VARIABLE_TAG_START, VARIABLE_TAG_END, SINGLE_BRACE_START, SINGLE_BRACE_END, COMMENT_TAG_START, COMMENT_TAG_END
  7. from django.template.base import get_library, Library, InvalidTemplateLibrary
  8. from django.template.smartif import IfParser, Literal
  9. from django.conf import settings
  10. from django.utils.encoding import smart_str, smart_unicode
  11. from django.utils.safestring import mark_safe
  12. register = Library()
  13. # Regex for token keyword arguments
  14. kwarg_re = re.compile(r"(?:(\w+)=)?(.+)")
  15. def token_kwargs(bits, parser, support_legacy=False):
  16. """
  17. A utility method for parsing token keyword arguments.
  18. :param bits: A list containing remainder of the token (split by spaces)
  19. that is to be checked for arguments. Valid arguments will be removed
  20. from this list.
  21. :param support_legacy: If set to true ``True``, the legacy format
  22. ``1 as foo`` will be accepted. Otherwise, only the standard ``foo=1``
  23. format is allowed.
  24. :returns: A dictionary of the arguments retrieved from the ``bits`` token
  25. list.
  26. There is no requirement for all remaining token ``bits`` to be keyword
  27. arguments, so the dictionary will be returned as soon as an invalid
  28. argument format is reached.
  29. """
  30. if not bits:
  31. return {}
  32. match = kwarg_re.match(bits[0])
  33. kwarg_format = match and match.group(1)
  34. if not kwarg_format:
  35. if not support_legacy:
  36. return {}
  37. if len(bits) < 3 or bits[1] != 'as':
  38. return {}
  39. kwargs = {}
  40. while bits:
  41. if kwarg_format:
  42. match = kwarg_re.match(bits[0])
  43. if not match or not match.group(1):
  44. return kwargs
  45. key, value = match.groups()
  46. del bits[:1]
  47. else:
  48. if len(bits) < 3 or bits[1] != 'as':
  49. return kwargs
  50. key, value = bits[2], bits[0]
  51. del bits[:3]
  52. kwargs[key] = parser.compile_filter(value)
  53. if bits and not kwarg_format:
  54. if bits[0] != 'and':
  55. return kwargs
  56. del bits[:1]
  57. return kwargs
  58. class AutoEscapeControlNode(Node):
  59. """Implements the actions of the autoescape tag."""
  60. def __init__(self, setting, nodelist):
  61. self.setting, self.nodelist = setting, nodelist
  62. def render(self, context):
  63. old_setting = context.autoescape
  64. context.autoescape = self.setting
  65. output = self.nodelist.render(context)
  66. context.autoescape = old_setting
  67. if self.setting:
  68. return mark_safe(output)
  69. else:
  70. return output
  71. class CommentNode(Node):
  72. def render(self, context):
  73. return ''
  74. class CsrfTokenNode(Node):
  75. def render(self, context):
  76. csrf_token = context.get('csrf_token', None)
  77. if csrf_token:
  78. if csrf_token == 'NOTPROVIDED':
  79. return mark_safe(u"")
  80. else:
  81. return mark_safe(u"<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='%s' /></div>" % csrf_token)
  82. else:
  83. # It's very probable that the token is missing because of
  84. # misconfiguration, so we raise a warning
  85. from django.conf import settings
  86. if settings.DEBUG:
  87. import warnings
  88. warnings.warn("A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.")
  89. return u''
  90. class CycleNode(Node):
  91. def __init__(self, cyclevars, variable_name=None, silent=False):
  92. self.cyclevars = cyclevars
  93. self.variable_name = variable_name
  94. self.silent = silent
  95. def render(self, context):
  96. if self not in context.render_context:
  97. # First time the node is rendered in template
  98. context.render_context[self] = itertools_cycle(self.cyclevars)
  99. if self.silent:
  100. return ''
  101. cycle_iter = context.render_context[self]
  102. value = cycle_iter.next().resolve(context)
  103. if self.variable_name:
  104. context[self.variable_name] = value
  105. return value
  106. class DebugNode(Node):
  107. def render(self, context):
  108. from pprint import pformat
  109. output = [pformat(val) for val in context]
  110. output.append('\n\n')
  111. output.append(pformat(sys.modules))
  112. return ''.join(output)
  113. class FilterNode(Node):
  114. def __init__(self, filter_expr, nodelist):
  115. self.filter_expr, self.nodelist = filter_expr, nodelist
  116. def render(self, context):
  117. output = self.nodelist.render(context)
  118. # Apply filters.
  119. context.update({'var': output})
  120. filtered = self.filter_expr.resolve(context)
  121. context.pop()
  122. return filtered
  123. class FirstOfNode(Node):
  124. def __init__(self, vars):
  125. self.vars = vars
  126. def render(self, context):
  127. for var in self.vars:
  128. value = var.resolve(context, True)
  129. if value:
  130. return smart_unicode(value)
  131. return u''
  132. class ForNode(Node):
  133. child_nodelists = ('nodelist_loop', 'nodelist_empty')
  134. def __init__(self, loopvars, sequence, is_reversed, nodelist_loop, nodelist_empty=None):
  135. self.loopvars, self.sequence = loopvars, sequence
  136. self.is_reversed = is_reversed
  137. self.nodelist_loop = nodelist_loop
  138. if nodelist_empty is None:
  139. self.nodelist_empty = NodeList()
  140. else:
  141. self.nodelist_empty = nodelist_empty
  142. def __repr__(self):
  143. reversed_text = self.is_reversed and ' reversed' or ''
  144. return "<For Node: for %s in %s, tail_len: %d%s>" % \
  145. (', '.join(self.loopvars), self.sequence, len(self.nodelist_loop),
  146. reversed_text)
  147. def __iter__(self):
  148. for node in self.nodelist_loop:
  149. yield node
  150. for node in self.nodelist_empty:
  151. yield node
  152. def render(self, context):
  153. if 'forloop' in context:
  154. parentloop = context['forloop']
  155. else:
  156. parentloop = {}
  157. context.push()
  158. try:
  159. values = self.sequence.resolve(context, True)
  160. except VariableDoesNotExist:
  161. values = []
  162. if values is None:
  163. values = []
  164. if not hasattr(values, '__len__'):
  165. values = list(values)
  166. len_values = len(values)
  167. if len_values < 1:
  168. context.pop()
  169. return self.nodelist_empty.render(context)
  170. nodelist = NodeList()
  171. if self.is_reversed:
  172. values = reversed(values)
  173. unpack = len(self.loopvars) > 1
  174. # Create a forloop value in the context. We'll update counters on each
  175. # iteration just below.
  176. loop_dict = context['forloop'] = {'parentloop': parentloop}
  177. for i, item in enumerate(values):
  178. # Shortcuts for current loop iteration number.
  179. loop_dict['counter0'] = i
  180. loop_dict['counter'] = i+1
  181. # Reverse counter iteration numbers.
  182. loop_dict['revcounter'] = len_values - i
  183. loop_dict['revcounter0'] = len_values - i - 1
  184. # Boolean values designating first and last times through loop.
  185. loop_dict['first'] = (i == 0)
  186. loop_dict['last'] = (i == len_values - 1)
  187. pop_context = False
  188. if unpack:
  189. # If there are multiple loop variables, unpack the item into
  190. # them.
  191. try:
  192. unpacked_vars = dict(zip(self.loopvars, item))
  193. except TypeError:
  194. pass
  195. else:
  196. pop_context = True
  197. context.update(unpacked_vars)
  198. else:
  199. context[self.loopvars[0]] = item
  200. for node in self.nodelist_loop:
  201. nodelist.append(node.render(context))
  202. if pop_context:
  203. # The loop variables were pushed on to the context so pop them
  204. # off again. This is necessary because the tag lets the length
  205. # of loopvars differ to the length of each set of items and we
  206. # don't want to leave any vars from the previous loop on the
  207. # context.
  208. context.pop()
  209. context.pop()
  210. return nodelist.render(context)
  211. class IfChangedNode(Node):
  212. child_nodelists = ('nodelist_true', 'nodelist_false')
  213. def __init__(self, nodelist_true, nodelist_false, *varlist):
  214. self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
  215. self._last_seen = None
  216. self._varlist = varlist
  217. self._id = str(id(self))
  218. def render(self, context):
  219. if 'forloop' in context and self._id not in context['forloop']:
  220. self._last_seen = None
  221. context['forloop'][self._id] = 1
  222. try:
  223. if self._varlist:
  224. # Consider multiple parameters. This automatically behaves
  225. # like an OR evaluation of the multiple variables.
  226. compare_to = [var.resolve(context, True) for var in self._varlist]
  227. else:
  228. compare_to = self.nodelist_true.render(context)
  229. except VariableDoesNotExist:
  230. compare_to = None
  231. if compare_to != self._last_seen:
  232. firstloop = (self._last_seen == None)
  233. self._last_seen = compare_to
  234. content = self.nodelist_true.render(context)
  235. return content
  236. elif self.nodelist_false:
  237. return self.nodelist_false.render(context)
  238. return ''
  239. class IfEqualNode(Node):
  240. child_nodelists = ('nodelist_true', 'nodelist_false')
  241. def __init__(self, var1, var2, nodelist_true, nodelist_false, negate):
  242. self.var1, self.var2 = var1, var2
  243. self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
  244. self.negate = negate
  245. def __repr__(self):
  246. return "<IfEqualNode>"
  247. def render(self, context):
  248. val1 = self.var1.resolve(context, True)
  249. val2 = self.var2.resolve(context, True)
  250. if (self.negate and val1 != val2) or (not self.negate and val1 == val2):
  251. return self.nodelist_true.render(context)
  252. return self.nodelist_false.render(context)
  253. class IfNode(Node):
  254. child_nodelists = ('nodelist_true', 'nodelist_false')
  255. def __init__(self, var, nodelist_true, nodelist_false=None):
  256. self.nodelist_true, self.nodelist_false = nodelist_true, nodelist_false
  257. self.var = var
  258. def __repr__(self):
  259. return "<If node>"
  260. def __iter__(self):
  261. for node in self.nodelist_true:
  262. yield node
  263. for node in self.nodelist_false:
  264. yield node
  265. def render(self, context):
  266. try:
  267. var = self.var.eval(context)
  268. except VariableDoesNotExist:
  269. var = None
  270. if var:
  271. return self.nodelist_true.render(context)
  272. else:
  273. return self.nodelist_false.render(context)
  274. class RegroupNode(Node):
  275. def __init__(self, target, expression, var_name):
  276. self.target, self.expression = target, expression
  277. self.var_name = var_name
  278. def render(self, context):
  279. obj_list = self.target.resolve(context, True)
  280. if obj_list == None:
  281. # target variable wasn't found in context; fail silently.
  282. context[self.var_name] = []
  283. return ''
  284. # List of dictionaries in the format:
  285. # {'grouper': 'key', 'list': [list of contents]}.
  286. context[self.var_name] = [
  287. {'grouper': key, 'list': list(val)}
  288. for key, val in
  289. groupby(obj_list, lambda v, f=self.expression.resolve: f(v, True))
  290. ]
  291. return ''
  292. def include_is_allowed(filepath):
  293. for root in settings.ALLOWED_INCLUDE_ROOTS:
  294. if filepath.startswith(root):
  295. return True
  296. return False
  297. class SsiNode(Node):
  298. def __init__(self, filepath, parsed, legacy_filepath=True):
  299. self.filepath = filepath
  300. self.parsed = parsed
  301. self.legacy_filepath = legacy_filepath
  302. def render(self, context):
  303. filepath = self.filepath
  304. if not self.legacy_filepath:
  305. filepath = filepath.resolve(context)
  306. if not include_is_allowed(filepath):
  307. if settings.DEBUG:
  308. return "[Didn't have permission to include file]"
  309. else:
  310. return '' # Fail silently for invalid includes.
  311. try:
  312. fp = open(filepath, 'r')
  313. output = fp.read()
  314. fp.close()
  315. except IOError:
  316. output = ''
  317. if self.parsed:
  318. try:
  319. t = Template(output, name=filepath)
  320. return t.render(context)
  321. except TemplateSyntaxError, e:
  322. if settings.DEBUG:
  323. return "[Included template had syntax error: %s]" % e
  324. else:
  325. return '' # Fail silently for invalid included templates.
  326. return output
  327. class LoadNode(Node):
  328. def render(self, context):
  329. return ''
  330. class NowNode(Node):
  331. def __init__(self, format_string):
  332. self.format_string = format_string
  333. def render(self, context):
  334. from datetime import datetime
  335. from django.utils.dateformat import DateFormat
  336. df = DateFormat(datetime.now())
  337. return df.format(self.format_string)
  338. class SpacelessNode(Node):
  339. def __init__(self, nodelist):
  340. self.nodelist = nodelist
  341. def render(self, context):
  342. from django.utils.html import strip_spaces_between_tags
  343. return strip_spaces_between_tags(self.nodelist.render(context).strip())
  344. class TemplateTagNode(Node):
  345. mapping = {'openblock': BLOCK_TAG_START,
  346. 'closeblock': BLOCK_TAG_END,
  347. 'openvariable': VARIABLE_TAG_START,
  348. 'closevariable': VARIABLE_TAG_END,
  349. 'openbrace': SINGLE_BRACE_START,
  350. 'closebrace': SINGLE_BRACE_END,
  351. 'opencomment': COMMENT_TAG_START,
  352. 'closecomment': COMMENT_TAG_END,
  353. }
  354. def __init__(self, tagtype):
  355. self.tagtype = tagtype
  356. def render(self, context):
  357. return self.mapping.get(self.tagtype, '')
  358. class URLNode(Node):
  359. def __init__(self, view_name, args, kwargs, asvar, legacy_view_name=True):
  360. self.view_name = view_name
  361. self.legacy_view_name = legacy_view_name
  362. self.args = args
  363. self.kwargs = kwargs
  364. self.asvar = asvar
  365. def render(self, context):
  366. from django.core.urlresolvers import reverse, NoReverseMatch
  367. args = [arg.resolve(context) for arg in self.args]
  368. kwargs = dict([(smart_str(k, 'ascii'), v.resolve(context))
  369. for k, v in self.kwargs.items()])
  370. view_name = self.view_name
  371. if not self.legacy_view_name:
  372. view_name = view_name.resolve(context)
  373. # Try to look up the URL twice: once given the view name, and again
  374. # relative to what we guess is the "main" app. If they both fail,
  375. # re-raise the NoReverseMatch unless we're using the
  376. # {% url ... as var %} construct in which cause return nothing.
  377. url = ''
  378. try:
  379. url = reverse(view_name, args=args, kwargs=kwargs, current_app=context.current_app)
  380. except NoReverseMatch, e:
  381. if settings.SETTINGS_MODULE:
  382. project_name = settings.SETTINGS_MODULE.split('.')[0]
  383. try:
  384. url = reverse(project_name + '.' + view_name,
  385. args=args, kwargs=kwargs,
  386. current_app=context.current_app)
  387. except NoReverseMatch:
  388. if self.asvar is None:
  389. # Re-raise the original exception, not the one with
  390. # the path relative to the project. This makes a
  391. # better error message.
  392. raise e
  393. else:
  394. if self.asvar is None:
  395. raise e
  396. if self.asvar:
  397. context[self.asvar] = url
  398. return ''
  399. else:
  400. return url
  401. class WidthRatioNode(Node):
  402. def __init__(self, val_expr, max_expr, max_width):
  403. self.val_expr = val_expr
  404. self.max_expr = max_expr
  405. self.max_width = max_width
  406. def render(self, context):
  407. try:
  408. value = self.val_expr.resolve(context)
  409. maxvalue = self.max_expr.resolve(context)
  410. max_width = int(self.max_width.resolve(context))
  411. except VariableDoesNotExist:
  412. return ''
  413. except ValueError:
  414. raise TemplateSyntaxError("widthratio final argument must be an number")
  415. try:
  416. value = float(value)
  417. maxvalue = float(maxvalue)
  418. ratio = (value / maxvalue) * max_width
  419. except (ValueError, ZeroDivisionError):
  420. return ''
  421. return str(int(round(ratio)))
  422. class WithNode(Node):
  423. def __init__(self, var, name, nodelist, extra_context=None,
  424. isolated_context=False):
  425. self.nodelist = nodelist
  426. # var and name are legacy attributes, being left in case they are used
  427. # by third-party subclasses of this Node.
  428. self.extra_context = extra_context or {}
  429. if name:
  430. self.extra_context[name] = var
  431. self.isolated_context = isolated_context
  432. def __repr__(self):
  433. return "<WithNode>"
  434. def render(self, context):
  435. values = dict([(key, val.resolve(context)) for key, val in
  436. self.extra_context.iteritems()])
  437. if self.isolated_context:
  438. return self.nodelist.render(Context(values))
  439. context.update(values)
  440. output = self.nodelist.render(context)
  441. context.pop()
  442. return output
  443. #@register.tag
  444. def autoescape(parser, token):
  445. """
  446. Force autoescape behaviour for this block.
  447. """
  448. args = token.contents.split()
  449. if len(args) != 2:
  450. raise TemplateSyntaxError("'autoescape' tag requires exactly one argument.")
  451. arg = args[1]
  452. if arg not in (u'on', u'off'):
  453. raise TemplateSyntaxError("'autoescape' argument should be 'on' or 'off'")
  454. nodelist = parser.parse(('endautoescape',))
  455. parser.delete_first_token()
  456. return AutoEscapeControlNode((arg == 'on'), nodelist)
  457. autoescape = register.tag(autoescape)
  458. #@register.tag
  459. def comment(parser, token):
  460. """
  461. Ignores everything between ``{% comment %}`` and ``{% endcomment %}``.
  462. """
  463. parser.skip_past('endcomment')
  464. return CommentNode()
  465. comment = register.tag(comment)
  466. #@register.tag
  467. def cycle(parser, token):
  468. """
  469. Cycles among the given strings each time this tag is encountered.
  470. Within a loop, cycles among the given strings each time through
  471. the loop::
  472. {% for o in some_list %}
  473. <tr class="{% cycle 'row1' 'row2' %}">
  474. ...
  475. </tr>
  476. {% endfor %}
  477. Outside of a loop, give the values a unique name the first time you call
  478. it, then use that name each sucessive time through::
  479. <tr class="{% cycle 'row1' 'row2' 'row3' as rowcolors %}">...</tr>
  480. <tr class="{% cycle rowcolors %}">...</tr>
  481. <tr class="{% cycle rowcolors %}">...</tr>
  482. You can use any number of values, separated by spaces. Commas can also
  483. be used to separate values; if a comma is used, the cycle values are
  484. interpreted as literal strings.
  485. The optional flag "silent" can be used to prevent the cycle declaration
  486. from returning any value::
  487. {% cycle 'row1' 'row2' as rowcolors silent %}{# no value here #}
  488. {% for o in some_list %}
  489. <tr class="{% cycle rowcolors %}">{# first value will be "row1" #}
  490. ...
  491. </tr>
  492. {% endfor %}
  493. """
  494. # Note: This returns the exact same node on each {% cycle name %} call;
  495. # that is, the node object returned from {% cycle a b c as name %} and the
  496. # one returned from {% cycle name %} are the exact same object. This
  497. # shouldn't cause problems (heh), but if it does, now you know.
  498. #
  499. # Ugly hack warning: This stuffs the named template dict into parser so
  500. # that names are only unique within each template (as opposed to using
  501. # a global variable, which would make cycle names have to be unique across
  502. # *all* templates.
  503. args = token.split_contents()
  504. if len(args) < 2:
  505. raise TemplateSyntaxError("'cycle' tag requires at least two arguments")
  506. if ',' in args[1]:
  507. # Backwards compatibility: {% cycle a,b %} or {% cycle a,b as foo %}
  508. # case.
  509. args[1:2] = ['"%s"' % arg for arg in args[1].split(",")]
  510. if len(args) == 2:
  511. # {% cycle foo %} case.
  512. name = args[1]
  513. if not hasattr(parser, '_namedCycleNodes'):
  514. raise TemplateSyntaxError("No named cycles in template. '%s' is not defined" % name)
  515. if not name in parser._namedCycleNodes:
  516. raise TemplateSyntaxError("Named cycle '%s' does not exist" % name)
  517. return parser._namedCycleNodes[name]
  518. as_form = False
  519. if len(args) > 4:
  520. # {% cycle ... as foo [silent] %} case.
  521. if args[-3] == "as":
  522. if args[-1] != "silent":
  523. raise TemplateSyntaxError("Only 'silent' flag is allowed after cycle's name, not '%s'." % args[-1])
  524. as_form = True
  525. silent = True
  526. args = args[:-1]
  527. elif args[-2] == "as":
  528. as_form = True
  529. silent = False
  530. if as_form:
  531. name = args[-1]
  532. values = [parser.compile_filter(arg) for arg in args[1:-2]]
  533. node = CycleNode(values, name, silent=silent)
  534. if not hasattr(parser, '_namedCycleNodes'):
  535. parser._namedCycleNodes = {}
  536. parser._namedCycleNodes[name] = node
  537. else:
  538. values = [parser.compile_filter(arg) for arg in args[1:]]
  539. node = CycleNode(values)
  540. return node
  541. cycle = register.tag(cycle)
  542. def csrf_token(parser, token):
  543. return CsrfTokenNode()
  544. register.tag(csrf_token)
  545. def debug(parser, token):
  546. """
  547. Outputs a whole load of debugging information, including the current
  548. context and imported modules.
  549. Sample usage::
  550. <pre>
  551. {% debug %}
  552. </pre>
  553. """
  554. return DebugNode()
  555. debug = register.tag(debug)
  556. #@register.tag(name="filter")
  557. def do_filter(parser, token):
  558. """
  559. Filters the contents of the block through variable filters.
  560. Filters can also be piped through each other, and they can have
  561. arguments -- just like in variable syntax.
  562. Sample usage::
  563. {% filter force_escape|lower %}
  564. This text will be HTML-escaped, and will appear in lowercase.
  565. {% endfilter %}
  566. """
  567. _, rest = token.contents.split(None, 1)
  568. filter_expr = parser.compile_filter("var|%s" % (rest))
  569. for func, unused in filter_expr.filters:
  570. if getattr(func, '_decorated_function', func).__name__ in ('escape', 'safe'):
  571. raise TemplateSyntaxError('"filter %s" is not permitted. Use the "autoescape" tag instead.' % func.__name__)
  572. nodelist = parser.parse(('endfilter',))
  573. parser.delete_first_token()
  574. return FilterNode(filter_expr, nodelist)
  575. do_filter = register.tag("filter", do_filter)
  576. #@register.tag
  577. def firstof(parser, token):
  578. """
  579. Outputs the first variable passed that is not False, without escaping.
  580. Outputs nothing if all the passed variables are False.
  581. Sample usage::
  582. {% firstof var1 var2 var3 %}
  583. This is equivalent to::
  584. {% if var1 %}
  585. {{ var1|safe }}
  586. {% else %}{% if var2 %}
  587. {{ var2|safe }}
  588. {% else %}{% if var3 %}
  589. {{ var3|safe }}
  590. {% endif %}{% endif %}{% endif %}
  591. but obviously much cleaner!
  592. You can also use a literal string as a fallback value in case all
  593. passed variables are False::
  594. {% firstof var1 var2 var3 "fallback value" %}
  595. If you want to escape the output, use a filter tag::
  596. {% filter force_escape %}
  597. {% firstof var1 var2 var3 "fallback value" %}
  598. {% endfilter %}
  599. """
  600. bits = token.split_contents()[1:]
  601. if len(bits) < 1:
  602. raise TemplateSyntaxError("'firstof' statement requires at least one argument")
  603. return FirstOfNode([parser.compile_filter(bit) for bit in bits])
  604. firstof = register.tag(firstof)
  605. #@register.tag(name="for")
  606. def do_for(parser, token):
  607. """
  608. Loops over each item in an array.
  609. For example, to display a list of athletes given ``athlete_list``::
  610. <ul>
  611. {% for athlete in athlete_list %}
  612. <li>{{ athlete.name }}</li>
  613. {% endfor %}
  614. </ul>
  615. You can loop over a list in reverse by using
  616. ``{% for obj in list reversed %}``.
  617. You can also unpack multiple values from a two-dimensional array::
  618. {% for key,value in dict.items %}
  619. {{ key }}: {{ value }}
  620. {% endfor %}
  621. The ``for`` tag can take an optional ``{% empty %}`` clause that will
  622. be displayed if the given array is empty or could not be found::
  623. <ul>
  624. {% for athlete in athlete_list %}
  625. <li>{{ athlete.name }}</li>
  626. {% empty %}
  627. <li>Sorry, no athletes in this list.</li>
  628. {% endfor %}
  629. <ul>
  630. The above is equivalent to -- but shorter, cleaner, and possibly faster
  631. than -- the following::
  632. <ul>
  633. {% if althete_list %}
  634. {% for athlete in athlete_list %}
  635. <li>{{ athlete.name }}</li>
  636. {% endfor %}
  637. {% else %}
  638. <li>Sorry, no athletes in this list.</li>
  639. {% endif %}
  640. </ul>
  641. The for loop sets a number of variables available within the loop:
  642. ========================== ================================================
  643. Variable Description
  644. ========================== ================================================
  645. ``forloop.counter`` The current iteration of the loop (1-indexed)
  646. ``forloop.counter0`` The current iteration of the loop (0-indexed)
  647. ``forloop.revcounter`` The number of iterations from the end of the
  648. loop (1-indexed)
  649. ``forloop.revcounter0`` The number of iterations from the end of the
  650. loop (0-indexed)
  651. ``forloop.first`` True if this is the first time through the loop
  652. ``forloop.last`` True if this is the last time through the loop
  653. ``forloop.parentloop`` For nested loops, this is the loop "above" the
  654. current one
  655. ========================== ================================================
  656. """
  657. bits = token.contents.split()
  658. if len(bits) < 4:
  659. raise TemplateSyntaxError("'for' statements should have at least four"
  660. " words: %s" % token.contents)
  661. is_reversed = bits[-1] == 'reversed'
  662. in_index = is_reversed and -3 or -2
  663. if bits[in_index] != 'in':
  664. raise TemplateSyntaxError("'for' statements should use the format"
  665. " 'for x in y': %s" % token.contents)
  666. loopvars = re.split(r' *, *', ' '.join(bits[1:in_index]))
  667. for var in loopvars:
  668. if not var or ' ' in var:
  669. raise TemplateSyntaxError("'for' tag received an invalid argument:"
  670. " %s" % token.contents)
  671. sequence = parser.compile_filter(bits[in_index+1])
  672. nodelist_loop = parser.parse(('empty', 'endfor',))
  673. token = parser.next_token()
  674. if token.contents == 'empty':
  675. nodelist_empty = parser.parse(('endfor',))
  676. parser.delete_first_token()
  677. else:
  678. nodelist_empty = None
  679. return ForNode(loopvars, sequence, is_reversed, nodelist_loop, nodelist_empty)
  680. do_for = register.tag("for", do_for)
  681. def do_ifequal(parser, token, negate):
  682. bits = list(token.split_contents())
  683. if len(bits) != 3:
  684. raise TemplateSyntaxError("%r takes two arguments" % bits[0])
  685. end_tag = 'end' + bits[0]
  686. nodelist_true = parser.parse(('else', end_tag))
  687. token = parser.next_token()
  688. if token.contents == 'else':
  689. nodelist_false = parser.parse((end_tag,))
  690. parser.delete_first_token()
  691. else:
  692. nodelist_false = NodeList()
  693. val1 = parser.compile_filter(bits[1])
  694. val2 = parser.compile_filter(bits[2])
  695. return IfEqualNode(val1, val2, nodelist_true, nodelist_false, negate)
  696. #@register.tag
  697. def ifequal(parser, token):
  698. """
  699. Outputs the contents of the block if the two arguments equal each other.
  700. Examples::
  701. {% ifequal user.id comment.user_id %}
  702. ...
  703. {% endifequal %}
  704. {% ifnotequal user.id comment.user_id %}
  705. ...
  706. {% else %}
  707. ...
  708. {% endifnotequal %}
  709. """
  710. return do_ifequal(parser, token, False)
  711. ifequal = register.tag(ifequal)
  712. #@register.tag
  713. def ifnotequal(parser, token):
  714. """
  715. Outputs the contents of the block if the two arguments are not equal.
  716. See ifequal.
  717. """
  718. return do_ifequal(parser, token, True)
  719. ifnotequal = register.tag(ifnotequal)
  720. class TemplateLiteral(Literal):
  721. def __init__(self, value, text):
  722. self.value = value
  723. self.text = text # for better error messages
  724. def display(self):
  725. return self.text
  726. def eval(self, context):
  727. return self.value.resolve(context, ignore_failures=True)
  728. class TemplateIfParser(IfParser):
  729. error_class = TemplateSyntaxError
  730. def __init__(self, parser, *args, **kwargs):
  731. self.template_parser = parser
  732. return super(TemplateIfParser, self).__init__(*args, **kwargs)
  733. def create_var(self, value):
  734. return TemplateLiteral(self.template_parser.compile_filter(value), value)
  735. #@register.tag(name="if")
  736. def do_if(parser, token):
  737. """
  738. The ``{% if %}`` tag evaluates a variable, and if that variable is "true"
  739. (i.e., exists, is not empty, and is not a false boolean value), the
  740. contents of the block are output:
  741. ::
  742. {% if athlete_list %}
  743. Number of athletes: {{ athlete_list|count }}
  744. {% else %}
  745. No athletes.
  746. {% endif %}
  747. In the above, if ``athlete_list`` is not empty, the number of athletes will
  748. be displayed by the ``{{ athlete_list|count }}`` variable.
  749. As you can see, the ``if`` tag can take an option ``{% else %}`` clause
  750. that will be displayed if the test fails.
  751. ``if`` tags may use ``or``, ``and`` or ``not`` to test a number of
  752. variables or to negate a given variable::
  753. {% if not athlete_list %}
  754. There are no athletes.
  755. {% endif %}
  756. {% if athlete_list or coach_list %}
  757. There are some athletes or some coaches.
  758. {% endif %}
  759. {% if athlete_list and coach_list %}
  760. Both atheletes and coaches are available.
  761. {% endif %}
  762. {% if not athlete_list or coach_list %}
  763. There are no athletes, or there are some coaches.
  764. {% endif %}
  765. {% if athlete_list and not coach_list %}
  766. There are some athletes and absolutely no coaches.
  767. {% endif %}
  768. Comparison operators are also available, and the use of filters is also
  769. allowed, for example::
  770. {% if articles|length >= 5 %}...{% endif %}
  771. Arguments and operators _must_ have a space between them, so
  772. ``{% if 1>2 %}`` is not a valid if tag.
  773. All supported operators are: ``or``, ``and``, ``in``, ``not in``
  774. ``==`` (or ``=``), ``!=``, ``>``, ``>=``, ``<`` and ``<=``.
  775. Operator precedence follows Python.
  776. """
  777. bits = token.split_contents()[1:]
  778. var = TemplateIfParser(parser, bits).parse()
  779. nodelist_true = parser.parse(('else', 'endif'))
  780. token = parser.next_token()
  781. if token.contents == 'else':
  782. nodelist_false = parser.parse(('endif',))
  783. parser.delete_first_token()
  784. else:
  785. nodelist_false = NodeList()
  786. return IfNode(var, nodelist_true, nodelist_false)
  787. do_if = register.tag("if", do_if)
  788. #@register.tag
  789. def ifchanged(parser, token):
  790. """
  791. Checks if a value has changed from the last iteration of a loop.
  792. The 'ifchanged' block tag is used within a loop. It has two possible uses.
  793. 1. Checks its own rendered contents against its previous state and only
  794. displays the content if it has changed. For example, this displays a
  795. list of days, only displaying the month if it changes::
  796. <h1>Archive for {{ year }}</h1>
  797. {% for date in days %}
  798. {% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %}
  799. <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a>
  800. {% endfor %}
  801. 2. If given a variable, check whether that variable has changed.
  802. For example, the following shows the date every time it changes, but
  803. only shows the hour if both the hour and the date have changed::
  804. {% for date in days %}
  805. {% ifchanged date.date %} {{ date.date }} {% endifchanged %}
  806. {% ifchanged date.hour date.date %}
  807. {{ date.hour }}
  808. {% endifchanged %}
  809. {% endfor %}
  810. """
  811. bits = token.contents.split()
  812. nodelist_true = parser.parse(('else', 'endifchanged'))
  813. token = parser.next_token()
  814. if token.contents == 'else':
  815. nodelist_false = parser.parse(('endifchanged',))
  816. parser.delete_first_token()
  817. else:
  818. nodelist_false = NodeList()
  819. values = [parser.compile_filter(bit) for bit in bits[1:]]
  820. return IfChangedNode(nodelist_true, nodelist_false, *values)
  821. ifchanged = register.tag(ifchanged)
  822. #@register.tag
  823. def ssi(parser, token):
  824. """
  825. Outputs the contents of a given file into the page.
  826. Like a simple "include" tag, the ``ssi`` tag includes the contents
  827. of another file -- which must be specified using an absolute path --
  828. in the current page::
  829. {% ssi /home/html/ljworld.com/includes/right_generic.html %}
  830. If the optional "parsed" parameter is given, the contents of the included
  831. file are evaluated as template code, with the current context::
  832. {% ssi /home/html/ljworld.com/includes/right_generic.html parsed %}
  833. """
  834. import warnings
  835. warnings.warn('The syntax for the ssi template tag is changing. Load the `ssi` tag from the `future` tag library to start using the new behavior.',
  836. category=PendingDeprecationWarning)
  837. bits = token.contents.split()
  838. parsed = False
  839. if len(bits) not in (2, 3):
  840. raise TemplateSyntaxError("'ssi' tag takes one argument: the path to"
  841. " the file to be included")
  842. if len(bits) == 3:
  843. if bits[2] == 'parsed':
  844. parsed = True
  845. else:
  846. raise TemplateSyntaxError("Second (optional) argument to %s tag"
  847. " must be 'parsed'" % bits[0])
  848. return SsiNode(bits[1], parsed, legacy_filepath=True)
  849. ssi = register.tag(ssi)
  850. #@register.tag
  851. def load(parser, token):
  852. """
  853. Loads a custom template tag set.
  854. For example, to load the template tags in
  855. ``django/templatetags/news/photos.py``::
  856. {% load news.photos %}
  857. Can also be used to load an individual tag/filter from
  858. a library::
  859. {% load byline from news %}
  860. """
  861. bits = token.contents.split()
  862. if len(bits) >= 4 and bits[-2] == "from":
  863. try:
  864. taglib = bits[-1]
  865. lib = get_library(taglib)
  866. except InvalidTemplateLibrary, e:
  867. raise TemplateSyntaxError("'%s' is not a valid tag library: %s" %
  868. (taglib, e))
  869. else:
  870. temp_lib = Library()
  871. for name in bits[1:-2]:
  872. if name in lib.tags:
  873. temp_lib.tags[name] = lib.tags[name]
  874. # a name could be a tag *and* a filter, so check for both
  875. if name in lib.filters:
  876. temp_lib.filters[name] = lib.filters[name]
  877. elif name in lib.filters:
  878. temp_lib.filters[name] = lib.filters[name]
  879. else:
  880. raise TemplateSyntaxError("'%s' is not a valid tag or filter in tag library '%s'" %
  881. (name, taglib))
  882. parser.add_library(temp_lib)
  883. else:
  884. for taglib in bits[1:]:
  885. # add the library to the parser
  886. try:
  887. lib = get_library(taglib)
  888. parser.add_library(lib)
  889. except InvalidTemplateLibrary, e:
  890. raise TemplateSyntaxError("'%s' is not a valid tag library: %s" %
  891. (taglib, e))
  892. return LoadNode()
  893. load = register.tag(load)
  894. #@register.tag
  895. def now(parser, token):
  896. """
  897. Displays the date, formatted according to the given string.
  898. Uses the same format as PHP's ``date()`` function; see http://php.net/date
  899. for all the possible values.
  900. Sample usage::
  901. It is {% now "jS F Y H:i" %}
  902. """
  903. bits = token.contents.split('"')
  904. if len(bits) != 3:
  905. raise TemplateSyntaxError("'now' statement takes one argument")
  906. format_string = bits[1]
  907. return NowNode(format_string)
  908. now = register.tag(now)
  909. #@register.tag
  910. def regroup(parser, token):
  911. """
  912. Regroups a list of alike objects by a common attribute.
  913. This complex tag is best illustrated by use of an example: say that
  914. ``people`` is a list of ``Person`` objects that have ``first_name``,
  915. ``last_name``, and ``gender`` attributes, and you'd like to display a list
  916. that looks like:
  917. * Male:
  918. * George Bush
  919. * Bill Clinton
  920. * Female:
  921. * Margaret Thatcher
  922. * Colendeeza Rice
  923. * Unknown:
  924. * Pat Smith
  925. The following snippet of template code would accomplish this dubious task::
  926. {% regroup people by gender as grouped %}
  927. <ul>
  928. {% for group in grouped %}
  929. <li>{{ group.grouper }}
  930. <ul>
  931. {% for item in group.list %}
  932. <li>{{ item }}</li>
  933. {% endfor %}
  934. </ul>
  935. {% endfor %}
  936. </ul>
  937. As you can see, ``{% regroup %}`` populates a variable with a list of
  938. objects with ``grouper`` and ``list`` attributes. ``grouper`` contains the
  939. item that was grouped by; ``list`` contains the list of objects that share
  940. that ``grouper``. In this case, ``grouper`` would be ``Male``, ``Female``
  941. and ``Unknown``, and ``list`` is the list of people with those genders.
  942. Note that ``{% regroup %}`` does not work when the list to be grouped is not
  943. sorted by the key you are grouping by! This means that if your list of
  944. people was not sorted by gender, you'd need to make sure it is sorted
  945. before using it, i.e.::
  946. {% regroup people|dictsort:"gender" by gender as grouped %}
  947. """
  948. firstbits = token.contents.split(None, 3)
  949. if len(firstbits) != 4:
  950. raise TemplateSyntaxError("'regroup' tag takes five arguments")
  951. target = parser.compile_filter(firstbits[1])
  952. if firstbits[2] != 'by':
  953. raise TemplateSyntaxError("second argument to 'regroup' tag must be 'by'")
  954. lastbits_reversed = firstbits[3][::-1].split(None, 2)
  955. if lastbits_reversed[1][::-1] != 'as':
  956. raise TemplateSyntaxError("next-to-last argument to 'regroup' tag must"
  957. " be 'as'")
  958. expression = parser.compile_filter(lastbits_reversed[2][::-1])
  959. var_name = lastbits_reversed[0][::-1]
  960. return RegroupNode(target, expression, var_name)
  961. regroup = register.tag(regroup)
  962. def spaceless(parser, token):
  963. """
  964. Removes whitespace between HTML tags, including tab and newline characters.
  965. Example usage::
  966. {% spaceless %}
  967. <p>
  968. <a href="foo/">Foo</a>
  969. </p>
  970. {% endspaceless %}
  971. This example would return this HTML::
  972. <p><a href="foo/">Foo</a></p>
  973. Only space between *tags* is normalized -- not space between tags and text.
  974. In this example, the space around ``Hello`` won't be stripped::
  975. {% spaceless %}
  976. <strong>
  977. Hello
  978. </strong>
  979. {% endspaceless %}
  980. """
  981. nodelist = parser.parse(('endspaceless',))
  982. parser.delete_first_token()
  983. return SpacelessNode(nodelist)
  984. spaceless = register.tag(spaceless)
  985. #@register.tag
  986. def templatetag(parser, token):
  987. """
  988. Outputs one of the bits used to compose template tags.
  989. Since the template system has no concept of "escaping", to display one of
  990. the bits used in template tags, you must use the ``{% templatetag %}`` tag.
  991. The argument tells which template bit to output:
  992. ================== =======
  993. Argument Outputs
  994. ================== =======
  995. ``openblock`` ``{%``
  996. ``closeblock`` ``%}``
  997. ``openvariable`` ``{{``
  998. ``closevariable`` ``}}``
  999. ``openbrace`` ``{``
  1000. ``closebrace`` ``}``
  1001. ``opencomment`` ``{#``
  1002. ``closecomment`` ``#}``
  1003. ================== =======
  1004. """
  1005. bits = token.contents.split()
  1006. if len(bits) != 2:
  1007. raise TemplateSyntaxError("'templatetag' statement takes one argument")
  1008. tag = bits[1]
  1009. if tag not in TemplateTagNode.mapping:
  1010. raise TemplateSyntaxError("Invalid templatetag argument: '%s'."
  1011. " Must be one of: %s" %
  1012. (tag, TemplateTagNode.mapping.keys()))
  1013. return TemplateTagNode(tag)
  1014. templatetag = register.tag(templatetag)
  1015. def url(parser, token):
  1016. """
  1017. Returns an absolute URL matching given view with its parameters.
  1018. This is a way to define links that aren't tied to a particular URL
  1019. configuration::
  1020. {% url path.to.some_view arg1 arg2 %}
  1021. or
  1022. {% url path.to.some_view name1=value1 name2=value2 %}
  1023. The first argument is a path to a view. It can be an absolute python path
  1024. or just ``app_name.view_name`` without the project name if the view is
  1025. located inside the project. Other arguments are comma-separated values
  1026. that will be filled in place of positional and keyword arguments in the
  1027. URL. All arguments for the URL should be present.
  1028. For example if you have a view ``app_name.client`` taking client's id and
  1029. the corresponding line in a URLconf looks like this::
  1030. ('^client/(\d+)/$', 'app_name.client')
  1031. and this app's URLconf is included into the project's URLconf under some
  1032. path::
  1033. ('^clients/', include('project_name.app_name.urls'))
  1034. then in a template you can create a link for a certain client like this::
  1035. {% url app_name.client client.id %}
  1036. The URL will look like ``/clients/client/123/``.
  1037. """
  1038. import warnings
  1039. warnings.warn('The syntax for the url template tag is changing. Load the `url` tag from the `future` tag library to start using the new behavior.',
  1040. category=PendingDeprecationWarning)
  1041. bits = token.split_contents()
  1042. if len(bits) < 2:
  1043. raise TemplateSyntaxError("'%s' takes at least one argument"
  1044. " (path to a view)" % bits[0])
  1045. viewname = bits[1]
  1046. args = []
  1047. kwargs = {}
  1048. asvar = None
  1049. bits = bits[2:]
  1050. if len(bits) >= 2 and bits[-2] == 'as':
  1051. asvar = bits[-1]
  1052. bits = bits[:-2]
  1053. # Backwards compatibility: check for the old comma separated format
  1054. # {% url urlname arg1,arg2 %}
  1055. # Initial check - that the first space separated bit has a comma in it
  1056. if bits and ',' in bits[0]:
  1057. check_old_format = True
  1058. # In order to *really* be old format, there must be a comma
  1059. # in *every* space separated bit, except the last.
  1060. for bit in bits[1:-1]:
  1061. if ',' not in bit:
  1062. # No comma in this bit. Either the comma we found
  1063. # in bit 1 was a false positive (e.g., comma in a string),
  1064. # or there is a syntax problem with missing commas
  1065. check_old_format = False
  1066. break
  1067. else:
  1068. # No comma found - must be new format.
  1069. check_old_format = False
  1070. if check_old_format:
  1071. # Confirm that this is old format by trying to parse the first
  1072. # argument. An exception will be raised if the comma is
  1073. # unexpected (i.e. outside of a static string).
  1074. match = kwarg_re.match(bits[0])
  1075. if match:
  1076. value = match.groups()[1]
  1077. try:
  1078. parser.compile_filter(value)
  1079. except TemplateSyntaxError:
  1080. bits = ''.join(bits).split(',')
  1081. # Now all the bits are parsed into new format,
  1082. # process them as template vars
  1083. if len(bits):
  1084. for bit in bits:
  1085. match = kwarg_re.match(bit)
  1086. if not match:
  1087. raise TemplateSyntaxError("Malformed arguments to url tag")
  1088. name, value = match.groups()
  1089. if name:
  1090. kwargs[name] = parser.compile_filter(value)
  1091. else:
  1092. args.append(parser.compile_filter(value))
  1093. return URLNode(viewname, args, kwargs, asvar, legacy_view_name=True)
  1094. url = register.tag(url)
  1095. #@register.tag
  1096. def widthratio(parser, token):
  1097. """
  1098. For creating bar charts and such, this tag calculates the ratio of a given
  1099. value to a maximum value, and then applies that ratio to a constant.
  1100. For example::
  1101. <img src='bar.gif' height='10' width='{% widthratio this_value max_value 100 %}' />
  1102. Above, if ``this_value`` is 175 and ``max_value`` is 200, the image in
  1103. the above example will be 88 pixels wide (because 175/200 = .875;
  1104. .875 * 100 = 87.5 which is rounded up to 88).
  1105. """
  1106. bits = token.contents.split()
  1107. if len(bits) != 4:
  1108. raise TemplateSyntaxError("widthratio takes three arguments")
  1109. tag, this_value_expr, max_value_expr, max_width = bits
  1110. return WidthRatioNode(parser.compile_filter(this_value_expr),
  1111. parser.compile_filter(max_value_expr),
  1112. parser.compile_filter(max_width))
  1113. widthratio = register.tag(widthratio)
  1114. #@register.tag
  1115. def do_with(parser, token):
  1116. """
  1117. Adds one or more values to the context (inside of this block) for caching
  1118. and easy access.
  1119. For example::
  1120. {% with total=person.some_sql_method %}
  1121. {{ total }} object{{ total|pluralize }}
  1122. {% endwith %}
  1123. Multiple values can be added to the context::
  1124. {% with foo=1 bar=2 %}
  1125. ...
  1126. {% endwith %}
  1127. The legacy format of ``{% with person.some_sql_method as total %}`` is
  1128. still accepted.
  1129. """
  1130. bits = token.split_contents()
  1131. remaining_bits = bits[1:]
  1132. extra_context = token_kwargs(remaining_bits, parser, support_legacy=True)
  1133. if not extra_context:
  1134. raise TemplateSyntaxError("%r expected at least one variable "
  1135. "assignment" % bits[0])
  1136. if remaining_bits:
  1137. raise TemplateSyntaxError("%r received an invalid token: %r" %
  1138. (bits[0], remaining_bits[0]))
  1139. nodelist = parser.parse(('endwith',))
  1140. parser.delete_first_token()
  1141. return WithNode(None, None, nodelist, extra_context=extra_context)
  1142. do_with = register.tag('with', do_with)