Filtering bool
to string
should give True
or False
respective of the value.
Filtering bool
to string
always gives False
.
Paste the template code (ideally a minimal example) that causes the issue
'{{6 > 0}}' ==> True
'{{6 > 0|string}}' ==> False
'{{6 > 0|bool}}' ==> True
'{{6 > 0|bool|string}}' ==> False
try (6>0)|...
or even better, a literal boolean such as true|...
or false|...
Yes, (6>0)|...
works. Why is this bug report closed?
Because it's not a bug, but simply operator precedence. Without parentheses your code was probably running as 6 > (0|string)
which obviously makes no sense, but in other operations such as 6 > '5'|int
it makes lots of sense, so this is neither a bug nor unintended behavior.
Coming from the Unix/Linux world where |
denotes a pipeline delimiter this is unexpected.
I think it should be 6 > ('5'|int)
insteads when needing such casts.
I disagree, and this would also be a massively breaking change.
Can we have a warning at least?
Real-world use-case for this is Ansible templating Java boolean properties:
isEnabled={{ some_var | length > 0 | string | lower }}
because I want isEnabled=true/false
instead of isEnabled=True/False
.
That would be more readable as isEnabled={{ ((some_var | length) > 0) | string | lower }}
(to me at least), which I believe would work as expected.
{{ (some_var|length > 0) | string | lower }}
More readable, and much clearer what it does
Well, I see we read it differently and Jinja currently reads it as you do. But the worst part of the above non-working example is it always silently gives False
.
I know Python is happy with that but do you think is it a good idea to issue a warning when using >
between int
and string
in Jinja templates?
Also please share your opinion on an |is_empty
filter to use instead of |lenght > 0
.
Anyway, thank you for your quick responses. Have a nice week.
Ansible can add this. Just like they did with |bool
which is not part of Jinja itself either.
I know Python is happy with that but do you think is it a good idea to issue a warning when using > between int and string in Jinja templates?
Haven't tested it, but probably it does fail in Python 3 where such comparisons fail loudly instead of silently succeeding with a somewhat useless result. Jinja does not do type checks, so it just passes the two operands to Python (didn't check the code, probably it calls operator.gt(a, b)
for it)
Nice to know, thank you.
Most helpful comment
More readable, and much clearer what it does