Limit a value to fall within a range

I found a clever python example for limiting a value to fall within a range and converted it for use in a Jinja2 template.

Let’s say you receive a value that must lie within the range of 0 to 100.

  • If the value is less than 0 it should be reported as 0.
  • If the value is greater than 100 it should be reported as 100.
  • Otherwise, report the value as-is.

The traditional way is to use arithmetic comparisons to check the value against the range-limits and, with some if-else involved, report the correct value.

Here’s the other way. Paste this into the Template Editor to see how it works.

{% set x = -12 %}
{{ ([0, x, 100]|sort)[1] }}

Screenshot from 2020-08-26 10-28-31

17 Likes

Clever! Bookmarked.

Much clearer than this method I have used:

IMG_0626

(Apologies for the screenshot, can’t cut and paste from the template editor in iOS).

1 Like