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 48KB

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