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