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.

defaultfilters.py 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. """Default variable filters."""
  2. import random as random_module
  3. import re
  4. import types
  5. from decimal import ROUND_HALF_UP, Context, Decimal, InvalidOperation
  6. from functools import wraps
  7. from operator import itemgetter
  8. from pprint import pformat
  9. from urllib.parse import quote
  10. from django.utils import formats
  11. from django.utils.dateformat import format, time_format
  12. from django.utils.encoding import iri_to_uri
  13. from django.utils.html import (
  14. avoid_wrapping, conditional_escape, escape, escapejs,
  15. json_script as _json_script, linebreaks, strip_tags, urlize as _urlize,
  16. )
  17. from django.utils.safestring import SafeData, mark_safe
  18. from django.utils.text import (
  19. Truncator, normalize_newlines, phone2numeric, slugify as _slugify, wrap,
  20. )
  21. from django.utils.timesince import timesince, timeuntil
  22. from django.utils.translation import gettext, ngettext
  23. from .base import Variable, VariableDoesNotExist
  24. from .library import Library
  25. register = Library()
  26. #######################
  27. # STRING DECORATOR #
  28. #######################
  29. def stringfilter(func):
  30. """
  31. Decorator for filters which should only receive strings. The object
  32. passed as the first positional argument will be converted to a string.
  33. """
  34. def _dec(*args, **kwargs):
  35. args = list(args)
  36. args[0] = str(args[0])
  37. if (isinstance(args[0], SafeData) and
  38. getattr(_dec._decorated_function, 'is_safe', False)):
  39. return mark_safe(func(*args, **kwargs))
  40. return func(*args, **kwargs)
  41. # Include a reference to the real function (used to check original
  42. # arguments by the template parser, and to bear the 'is_safe' attribute
  43. # when multiple decorators are applied).
  44. _dec._decorated_function = getattr(func, '_decorated_function', func)
  45. return wraps(func)(_dec)
  46. ###################
  47. # STRINGS #
  48. ###################
  49. @register.filter(is_safe=True)
  50. @stringfilter
  51. def addslashes(value):
  52. """
  53. Add slashes before quotes. Useful for escaping strings in CSV, for
  54. example. Less useful for escaping JavaScript; use the ``escapejs``
  55. filter instead.
  56. """
  57. return value.replace('\\', '\\\\').replace('"', '\\"').replace("'", "\\'")
  58. @register.filter(is_safe=True)
  59. @stringfilter
  60. def capfirst(value):
  61. """Capitalize the first character of the value."""
  62. return value and value[0].upper() + value[1:]
  63. @register.filter("escapejs")
  64. @stringfilter
  65. def escapejs_filter(value):
  66. """Hex encode characters for use in JavaScript strings."""
  67. return escapejs(value)
  68. @register.filter(is_safe=True)
  69. def json_script(value, element_id):
  70. """
  71. Output value JSON-encoded, wrapped in a <script type="application/json">
  72. tag.
  73. """
  74. return _json_script(value, element_id)
  75. @register.filter(is_safe=True)
  76. def floatformat(text, arg=-1):
  77. """
  78. Display a float to a specified number of decimal places.
  79. If called without an argument, display the floating point number with one
  80. decimal place -- but only if there's a decimal place to be displayed:
  81. * num1 = 34.23234
  82. * num2 = 34.00000
  83. * num3 = 34.26000
  84. * {{ num1|floatformat }} displays "34.2"
  85. * {{ num2|floatformat }} displays "34"
  86. * {{ num3|floatformat }} displays "34.3"
  87. If arg is positive, always display exactly arg number of decimal places:
  88. * {{ num1|floatformat:3 }} displays "34.232"
  89. * {{ num2|floatformat:3 }} displays "34.000"
  90. * {{ num3|floatformat:3 }} displays "34.260"
  91. If arg is negative, display arg number of decimal places -- but only if
  92. there are places to be displayed:
  93. * {{ num1|floatformat:"-3" }} displays "34.232"
  94. * {{ num2|floatformat:"-3" }} displays "34"
  95. * {{ num3|floatformat:"-3" }} displays "34.260"
  96. If the input float is infinity or NaN, display the string representation
  97. of that value.
  98. """
  99. try:
  100. input_val = repr(text)
  101. d = Decimal(input_val)
  102. except InvalidOperation:
  103. try:
  104. d = Decimal(str(float(text)))
  105. except (ValueError, InvalidOperation, TypeError):
  106. return ''
  107. try:
  108. p = int(arg)
  109. except ValueError:
  110. return input_val
  111. try:
  112. m = int(d) - d
  113. except (ValueError, OverflowError, InvalidOperation):
  114. return input_val
  115. if not m and p < 0:
  116. return mark_safe(formats.number_format('%d' % (int(d)), 0))
  117. exp = Decimal(1).scaleb(-abs(p))
  118. # Set the precision high enough to avoid an exception (#15789).
  119. tupl = d.as_tuple()
  120. units = len(tupl[1])
  121. units += -tupl[2] if m else tupl[2]
  122. prec = abs(p) + units + 1
  123. # Avoid conversion to scientific notation by accessing `sign`, `digits`,
  124. # and `exponent` from Decimal.as_tuple() directly.
  125. sign, digits, exponent = d.quantize(exp, ROUND_HALF_UP, Context(prec=prec)).as_tuple()
  126. digits = [str(digit) for digit in reversed(digits)]
  127. while len(digits) <= abs(exponent):
  128. digits.append('0')
  129. digits.insert(-exponent, '.')
  130. if sign:
  131. digits.append('-')
  132. number = ''.join(reversed(digits))
  133. return mark_safe(formats.number_format(number, abs(p)))
  134. @register.filter(is_safe=True)
  135. @stringfilter
  136. def iriencode(value):
  137. """Escape an IRI value for use in a URL."""
  138. return iri_to_uri(value)
  139. @register.filter(is_safe=True, needs_autoescape=True)
  140. @stringfilter
  141. def linenumbers(value, autoescape=True):
  142. """Display text with line numbers."""
  143. lines = value.split('\n')
  144. # Find the maximum width of the line count, for use with zero padding
  145. # string format command
  146. width = str(len(str(len(lines))))
  147. if not autoescape or isinstance(value, SafeData):
  148. for i, line in enumerate(lines):
  149. lines[i] = ("%0" + width + "d. %s") % (i + 1, line)
  150. else:
  151. for i, line in enumerate(lines):
  152. lines[i] = ("%0" + width + "d. %s") % (i + 1, escape(line))
  153. return mark_safe('\n'.join(lines))
  154. @register.filter(is_safe=True)
  155. @stringfilter
  156. def lower(value):
  157. """Convert a string into all lowercase."""
  158. return value.lower()
  159. @register.filter(is_safe=False)
  160. @stringfilter
  161. def make_list(value):
  162. """
  163. Return the value turned into a list.
  164. For an integer, it's a list of digits.
  165. For a string, it's a list of characters.
  166. """
  167. return list(value)
  168. @register.filter(is_safe=True)
  169. @stringfilter
  170. def slugify(value):
  171. """
  172. Convert to ASCII. Convert spaces to hyphens. Remove characters that aren't
  173. alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip
  174. leading and trailing whitespace.
  175. """
  176. return _slugify(value)
  177. @register.filter(is_safe=True)
  178. def stringformat(value, arg):
  179. """
  180. Format the variable according to the arg, a string formatting specifier.
  181. This specifier uses Python string formatting syntax, with the exception
  182. that the leading "%" is dropped.
  183. See https://docs.python.org/library/stdtypes.html#printf-style-string-formatting
  184. for documentation of Python string formatting.
  185. """
  186. if isinstance(value, tuple):
  187. value = str(value)
  188. try:
  189. return ("%" + str(arg)) % value
  190. except (ValueError, TypeError):
  191. return ""
  192. @register.filter(is_safe=True)
  193. @stringfilter
  194. def title(value):
  195. """Convert a string into titlecase."""
  196. t = re.sub("([a-z])'([A-Z])", lambda m: m.group(0).lower(), value.title())
  197. return re.sub(r"\d([A-Z])", lambda m: m.group(0).lower(), t)
  198. @register.filter(is_safe=True)
  199. @stringfilter
  200. def truncatechars(value, arg):
  201. """Truncate a string after `arg` number of characters."""
  202. try:
  203. length = int(arg)
  204. except ValueError: # Invalid literal for int().
  205. return value # Fail silently.
  206. return Truncator(value).chars(length)
  207. @register.filter(is_safe=True)
  208. @stringfilter
  209. def truncatechars_html(value, arg):
  210. """
  211. Truncate HTML after `arg` number of chars.
  212. Preserve newlines in the HTML.
  213. """
  214. try:
  215. length = int(arg)
  216. except ValueError: # invalid literal for int()
  217. return value # Fail silently.
  218. return Truncator(value).chars(length, html=True)
  219. @register.filter(is_safe=True)
  220. @stringfilter
  221. def truncatewords(value, arg):
  222. """
  223. Truncate a string after `arg` number of words.
  224. Remove newlines within the string.
  225. """
  226. try:
  227. length = int(arg)
  228. except ValueError: # Invalid literal for int().
  229. return value # Fail silently.
  230. return Truncator(value).words(length, truncate=' …')
  231. @register.filter(is_safe=True)
  232. @stringfilter
  233. def truncatewords_html(value, arg):
  234. """
  235. Truncate HTML after `arg` number of words.
  236. Preserve newlines in the HTML.
  237. """
  238. try:
  239. length = int(arg)
  240. except ValueError: # invalid literal for int()
  241. return value # Fail silently.
  242. return Truncator(value).words(length, html=True, truncate=' …')
  243. @register.filter(is_safe=False)
  244. @stringfilter
  245. def upper(value):
  246. """Convert a string into all uppercase."""
  247. return value.upper()
  248. @register.filter(is_safe=False)
  249. @stringfilter
  250. def urlencode(value, safe=None):
  251. """
  252. Escape a value for use in a URL.
  253. The ``safe`` parameter determines the characters which should not be
  254. escaped by Python's quote() function. If not provided, use the default safe
  255. characters (but an empty string can be provided when *all* characters
  256. should be escaped).
  257. """
  258. kwargs = {}
  259. if safe is not None:
  260. kwargs['safe'] = safe
  261. return quote(value, **kwargs)
  262. @register.filter(is_safe=True, needs_autoescape=True)
  263. @stringfilter
  264. def urlize(value, autoescape=True):
  265. """Convert URLs in plain text into clickable links."""
  266. return mark_safe(_urlize(value, nofollow=True, autoescape=autoescape))
  267. @register.filter(is_safe=True, needs_autoescape=True)
  268. @stringfilter
  269. def urlizetrunc(value, limit, autoescape=True):
  270. """
  271. Convert URLs into clickable links, truncating URLs to the given character
  272. limit, and adding 'rel=nofollow' attribute to discourage spamming.
  273. Argument: Length to truncate URLs to.
  274. """
  275. return mark_safe(_urlize(value, trim_url_limit=int(limit), nofollow=True, autoescape=autoescape))
  276. @register.filter(is_safe=False)
  277. @stringfilter
  278. def wordcount(value):
  279. """Return the number of words."""
  280. return len(value.split())
  281. @register.filter(is_safe=True)
  282. @stringfilter
  283. def wordwrap(value, arg):
  284. """Wrap words at `arg` line length."""
  285. return wrap(value, int(arg))
  286. @register.filter(is_safe=True)
  287. @stringfilter
  288. def ljust(value, arg):
  289. """Left-align the value in a field of a given width."""
  290. return value.ljust(int(arg))
  291. @register.filter(is_safe=True)
  292. @stringfilter
  293. def rjust(value, arg):
  294. """Right-align the value in a field of a given width."""
  295. return value.rjust(int(arg))
  296. @register.filter(is_safe=True)
  297. @stringfilter
  298. def center(value, arg):
  299. """Center the value in a field of a given width."""
  300. return value.center(int(arg))
  301. @register.filter
  302. @stringfilter
  303. def cut(value, arg):
  304. """Remove all values of arg from the given string."""
  305. safe = isinstance(value, SafeData)
  306. value = value.replace(arg, '')
  307. if safe and arg != ';':
  308. return mark_safe(value)
  309. return value
  310. ###################
  311. # HTML STRINGS #
  312. ###################
  313. @register.filter("escape", is_safe=True)
  314. @stringfilter
  315. def escape_filter(value):
  316. """Mark the value as a string that should be auto-escaped."""
  317. return conditional_escape(value)
  318. @register.filter(is_safe=True)
  319. @stringfilter
  320. def force_escape(value):
  321. """
  322. Escape a string's HTML. Return a new string containing the escaped
  323. characters (as opposed to "escape", which marks the content for later
  324. possible escaping).
  325. """
  326. return escape(value)
  327. @register.filter("linebreaks", is_safe=True, needs_autoescape=True)
  328. @stringfilter
  329. def linebreaks_filter(value, autoescape=True):
  330. """
  331. Replace line breaks in plain text with appropriate HTML; a single
  332. newline becomes an HTML line break (``<br>``) and a new line
  333. followed by a blank line becomes a paragraph break (``</p>``).
  334. """
  335. autoescape = autoescape and not isinstance(value, SafeData)
  336. return mark_safe(linebreaks(value, autoescape))
  337. @register.filter(is_safe=True, needs_autoescape=True)
  338. @stringfilter
  339. def linebreaksbr(value, autoescape=True):
  340. """
  341. Convert all newlines in a piece of plain text to HTML line breaks
  342. (``<br>``).
  343. """
  344. autoescape = autoescape and not isinstance(value, SafeData)
  345. value = normalize_newlines(value)
  346. if autoescape:
  347. value = escape(value)
  348. return mark_safe(value.replace('\n', '<br>'))
  349. @register.filter(is_safe=True)
  350. @stringfilter
  351. def safe(value):
  352. """Mark the value as a string that should not be auto-escaped."""
  353. return mark_safe(value)
  354. @register.filter(is_safe=True)
  355. def safeseq(value):
  356. """
  357. A "safe" filter for sequences. Mark each element in the sequence,
  358. individually, as safe, after converting them to strings. Return a list
  359. with the results.
  360. """
  361. return [mark_safe(obj) for obj in value]
  362. @register.filter(is_safe=True)
  363. @stringfilter
  364. def striptags(value):
  365. """Strip all [X]HTML tags."""
  366. return strip_tags(value)
  367. ###################
  368. # LISTS #
  369. ###################
  370. def _property_resolver(arg):
  371. """
  372. When arg is convertible to float, behave like operator.itemgetter(arg)
  373. Otherwise, behave like Variable(arg).resolve
  374. >>> _property_resolver(1)('abc')
  375. 'b'
  376. >>> _property_resolver('1')('abc')
  377. Traceback (most recent call last):
  378. ...
  379. TypeError: string indices must be integers
  380. >>> class Foo:
  381. ... a = 42
  382. ... b = 3.14
  383. ... c = 'Hey!'
  384. >>> _property_resolver('b')(Foo())
  385. 3.14
  386. """
  387. try:
  388. float(arg)
  389. except ValueError:
  390. return Variable(arg).resolve
  391. else:
  392. return itemgetter(arg)
  393. @register.filter(is_safe=False)
  394. def dictsort(value, arg):
  395. """
  396. Given a list of dicts, return that list sorted by the property given in
  397. the argument.
  398. """
  399. try:
  400. return sorted(value, key=_property_resolver(arg))
  401. except (TypeError, VariableDoesNotExist):
  402. return ''
  403. @register.filter(is_safe=False)
  404. def dictsortreversed(value, arg):
  405. """
  406. Given a list of dicts, return that list sorted in reverse order by the
  407. property given in the argument.
  408. """
  409. try:
  410. return sorted(value, key=_property_resolver(arg), reverse=True)
  411. except (TypeError, VariableDoesNotExist):
  412. return ''
  413. @register.filter(is_safe=False)
  414. def first(value):
  415. """Return the first item in a list."""
  416. try:
  417. return value[0]
  418. except IndexError:
  419. return ''
  420. @register.filter(is_safe=True, needs_autoescape=True)
  421. def join(value, arg, autoescape=True):
  422. """Join a list with a string, like Python's ``str.join(list)``."""
  423. try:
  424. if autoescape:
  425. value = [conditional_escape(v) for v in value]
  426. data = conditional_escape(arg).join(value)
  427. except TypeError: # Fail silently if arg isn't iterable.
  428. return value
  429. return mark_safe(data)
  430. @register.filter(is_safe=True)
  431. def last(value):
  432. """Return the last item in a list."""
  433. try:
  434. return value[-1]
  435. except IndexError:
  436. return ''
  437. @register.filter(is_safe=False)
  438. def length(value):
  439. """Return the length of the value - useful for lists."""
  440. try:
  441. return len(value)
  442. except (ValueError, TypeError):
  443. return 0
  444. @register.filter(is_safe=False)
  445. def length_is(value, arg):
  446. """Return a boolean of whether the value's length is the argument."""
  447. try:
  448. return len(value) == int(arg)
  449. except (ValueError, TypeError):
  450. return ''
  451. @register.filter(is_safe=True)
  452. def random(value):
  453. """Return a random item from the list."""
  454. return random_module.choice(value)
  455. @register.filter("slice", is_safe=True)
  456. def slice_filter(value, arg):
  457. """
  458. Return a slice of the list using the same syntax as Python's list slicing.
  459. """
  460. try:
  461. bits = []
  462. for x in str(arg).split(':'):
  463. if not x:
  464. bits.append(None)
  465. else:
  466. bits.append(int(x))
  467. return value[slice(*bits)]
  468. except (ValueError, TypeError):
  469. return value # Fail silently.
  470. @register.filter(is_safe=True, needs_autoescape=True)
  471. def unordered_list(value, autoescape=True):
  472. """
  473. Recursively take a self-nested list and return an HTML unordered list --
  474. WITHOUT opening and closing <ul> tags.
  475. Assume the list is in the proper format. For example, if ``var`` contains:
  476. ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then
  477. ``{{ var|unordered_list }}`` returns::
  478. <li>States
  479. <ul>
  480. <li>Kansas
  481. <ul>
  482. <li>Lawrence</li>
  483. <li>Topeka</li>
  484. </ul>
  485. </li>
  486. <li>Illinois</li>
  487. </ul>
  488. </li>
  489. """
  490. if autoescape:
  491. escaper = conditional_escape
  492. else:
  493. def escaper(x):
  494. return x
  495. def walk_items(item_list):
  496. item_iterator = iter(item_list)
  497. try:
  498. item = next(item_iterator)
  499. while True:
  500. try:
  501. next_item = next(item_iterator)
  502. except StopIteration:
  503. yield item, None
  504. break
  505. if isinstance(next_item, (list, tuple, types.GeneratorType)):
  506. try:
  507. iter(next_item)
  508. except TypeError:
  509. pass
  510. else:
  511. yield item, next_item
  512. item = next(item_iterator)
  513. continue
  514. yield item, None
  515. item = next_item
  516. except StopIteration:
  517. pass
  518. def list_formatter(item_list, tabs=1):
  519. indent = '\t' * tabs
  520. output = []
  521. for item, children in walk_items(item_list):
  522. sublist = ''
  523. if children:
  524. sublist = '\n%s<ul>\n%s\n%s</ul>\n%s' % (
  525. indent, list_formatter(children, tabs + 1), indent, indent)
  526. output.append('%s<li>%s%s</li>' % (
  527. indent, escaper(item), sublist))
  528. return '\n'.join(output)
  529. return mark_safe(list_formatter(value))
  530. ###################
  531. # INTEGERS #
  532. ###################
  533. @register.filter(is_safe=False)
  534. def add(value, arg):
  535. """Add the arg to the value."""
  536. try:
  537. return int(value) + int(arg)
  538. except (ValueError, TypeError):
  539. try:
  540. return value + arg
  541. except Exception:
  542. return ''
  543. @register.filter(is_safe=False)
  544. def get_digit(value, arg):
  545. """
  546. Given a whole number, return the requested digit of it, where 1 is the
  547. right-most digit, 2 is the second-right-most digit, etc. Return the
  548. original value for invalid input (if input or argument is not an integer,
  549. or if argument is less than 1). Otherwise, output is always an integer.
  550. """
  551. try:
  552. arg = int(arg)
  553. value = int(value)
  554. except ValueError:
  555. return value # Fail silently for an invalid argument
  556. if arg < 1:
  557. return value
  558. try:
  559. return int(str(value)[-arg])
  560. except IndexError:
  561. return 0
  562. ###################
  563. # DATES #
  564. ###################
  565. @register.filter(expects_localtime=True, is_safe=False)
  566. def date(value, arg=None):
  567. """Format a date according to the given format."""
  568. if value in (None, ''):
  569. return ''
  570. try:
  571. return formats.date_format(value, arg)
  572. except AttributeError:
  573. try:
  574. return format(value, arg)
  575. except AttributeError:
  576. return ''
  577. @register.filter(expects_localtime=True, is_safe=False)
  578. def time(value, arg=None):
  579. """Format a time according to the given format."""
  580. if value in (None, ''):
  581. return ''
  582. try:
  583. return formats.time_format(value, arg)
  584. except (AttributeError, TypeError):
  585. try:
  586. return time_format(value, arg)
  587. except (AttributeError, TypeError):
  588. return ''
  589. @register.filter("timesince", is_safe=False)
  590. def timesince_filter(value, arg=None):
  591. """Format a date as the time since that date (i.e. "4 days, 6 hours")."""
  592. if not value:
  593. return ''
  594. try:
  595. if arg:
  596. return timesince(value, arg)
  597. return timesince(value)
  598. except (ValueError, TypeError):
  599. return ''
  600. @register.filter("timeuntil", is_safe=False)
  601. def timeuntil_filter(value, arg=None):
  602. """Format a date as the time until that date (i.e. "4 days, 6 hours")."""
  603. if not value:
  604. return ''
  605. try:
  606. return timeuntil(value, arg)
  607. except (ValueError, TypeError):
  608. return ''
  609. ###################
  610. # LOGIC #
  611. ###################
  612. @register.filter(is_safe=False)
  613. def default(value, arg):
  614. """If value is unavailable, use given default."""
  615. return value or arg
  616. @register.filter(is_safe=False)
  617. def default_if_none(value, arg):
  618. """If value is None, use given default."""
  619. if value is None:
  620. return arg
  621. return value
  622. @register.filter(is_safe=False)
  623. def divisibleby(value, arg):
  624. """Return True if the value is divisible by the argument."""
  625. return int(value) % int(arg) == 0
  626. @register.filter(is_safe=False)
  627. def yesno(value, arg=None):
  628. """
  629. Given a string mapping values for true, false, and (optionally) None,
  630. return one of those strings according to the value:
  631. ========== ====================== ==================================
  632. Value Argument Outputs
  633. ========== ====================== ==================================
  634. ``True`` ``"yeah,no,maybe"`` ``yeah``
  635. ``False`` ``"yeah,no,maybe"`` ``no``
  636. ``None`` ``"yeah,no,maybe"`` ``maybe``
  637. ``None`` ``"yeah,no"`` ``"no"`` (converts None to False
  638. if no mapping for None is given.
  639. ========== ====================== ==================================
  640. """
  641. if arg is None:
  642. arg = gettext('yes,no,maybe')
  643. bits = arg.split(',')
  644. if len(bits) < 2:
  645. return value # Invalid arg.
  646. try:
  647. yes, no, maybe = bits
  648. except ValueError:
  649. # Unpack list of wrong size (no "maybe" value provided).
  650. yes, no, maybe = bits[0], bits[1], bits[1]
  651. if value is None:
  652. return maybe
  653. if value:
  654. return yes
  655. return no
  656. ###################
  657. # MISC #
  658. ###################
  659. @register.filter(is_safe=True)
  660. def filesizeformat(bytes_):
  661. """
  662. Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB,
  663. 102 bytes, etc.).
  664. """
  665. try:
  666. bytes_ = float(bytes_)
  667. except (TypeError, ValueError, UnicodeDecodeError):
  668. value = ngettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0}
  669. return avoid_wrapping(value)
  670. def filesize_number_format(value):
  671. return formats.number_format(round(value, 1), 1)
  672. KB = 1 << 10
  673. MB = 1 << 20
  674. GB = 1 << 30
  675. TB = 1 << 40
  676. PB = 1 << 50
  677. negative = bytes_ < 0
  678. if negative:
  679. bytes_ = -bytes_ # Allow formatting of negative numbers.
  680. if bytes_ < KB:
  681. value = ngettext("%(size)d byte", "%(size)d bytes", bytes_) % {'size': bytes_}
  682. elif bytes_ < MB:
  683. value = gettext("%s KB") % filesize_number_format(bytes_ / KB)
  684. elif bytes_ < GB:
  685. value = gettext("%s MB") % filesize_number_format(bytes_ / MB)
  686. elif bytes_ < TB:
  687. value = gettext("%s GB") % filesize_number_format(bytes_ / GB)
  688. elif bytes_ < PB:
  689. value = gettext("%s TB") % filesize_number_format(bytes_ / TB)
  690. else:
  691. value = gettext("%s PB") % filesize_number_format(bytes_ / PB)
  692. if negative:
  693. value = "-%s" % value
  694. return avoid_wrapping(value)
  695. @register.filter(is_safe=False)
  696. def pluralize(value, arg='s'):
  697. """
  698. Return a plural suffix if the value is not 1, '1', or an object of
  699. length 1. By default, use 's' as the suffix:
  700. * If value is 0, vote{{ value|pluralize }} display "votes".
  701. * If value is 1, vote{{ value|pluralize }} display "vote".
  702. * If value is 2, vote{{ value|pluralize }} display "votes".
  703. If an argument is provided, use that string instead:
  704. * If value is 0, class{{ value|pluralize:"es" }} display "classes".
  705. * If value is 1, class{{ value|pluralize:"es" }} display "class".
  706. * If value is 2, class{{ value|pluralize:"es" }} display "classes".
  707. If the provided argument contains a comma, use the text before the comma
  708. for the singular case and the text after the comma for the plural case:
  709. * If value is 0, cand{{ value|pluralize:"y,ies" }} display "candies".
  710. * If value is 1, cand{{ value|pluralize:"y,ies" }} display "candy".
  711. * If value is 2, cand{{ value|pluralize:"y,ies" }} display "candies".
  712. """
  713. if ',' not in arg:
  714. arg = ',' + arg
  715. bits = arg.split(',')
  716. if len(bits) > 2:
  717. return ''
  718. singular_suffix, plural_suffix = bits[:2]
  719. try:
  720. if float(value) != 1:
  721. return plural_suffix
  722. except ValueError: # Invalid string that's not a number.
  723. pass
  724. except TypeError: # Value isn't a string or a number; maybe it's a list?
  725. try:
  726. if len(value) != 1:
  727. return plural_suffix
  728. except TypeError: # len() of unsized object.
  729. pass
  730. return singular_suffix
  731. @register.filter("phone2numeric", is_safe=True)
  732. def phone2numeric_filter(value):
  733. """Take a phone number and converts it in to its numerical equivalent."""
  734. return phone2numeric(value)
  735. @register.filter(is_safe=True)
  736. def pprint(value):
  737. """A wrapper around pprint.pprint -- for debugging, really."""
  738. try:
  739. return pformat(value)
  740. except Exception as e:
  741. return "Error in formatting: %s: %s" % (e.__class__.__name__, e)