Development of an internal social media platform with personalised dashboards for students
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 49KB

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