You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

defaulttags.py 48KB

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