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 as0
. - If the value is greater than
100
it should be reported as100
. - 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] }}