'Is it possible to add a if condition inside tal:define?
I'm using python with Zope and I'm trying to create a variable with a if condition (if possible). I'm having a difficult time finding examples and resources online so I don't know if that's possible, but I do know that you can do something like this with variables
tal:define="
var1 python:(container.securityUtil.sanitize(path('result/h_or_e | nothing') or ''));
var2 python:container.util.get_strdate(renewDate, -adj3);
true_or_false python:var1 or var2;
"
So true_or_false will either be var1 or var2. So right now my code has a variable name initiated_by which checks a container to see if the path exists if it doesn't it equals an empty ' '. But instead of the empty string I want it to contain the word "blank". Here is my code.
tal:omit-tag=""
tal:repeat="result results">
tal:define="
certification python:container.securityUtil.sanitize((path('result/cert | nothing') or ''));
initiated_by python:(container.securityUtil.sanitize(path('result/h_or_e | nothing') or ''))
"
<button type="button" class="blend"
tal:content="python:initiated_by" tal:attributes="aria-label python:'Initiated by, %s, %s' % (certification, initiated_by)">
Initiated<br/>By
</button>
I can't see what the container path from "nothing" means or is but when I use devtools I can see that the field is empty. It's not from the empty ' ' because I tried putting blank inside the qoutes and nothing happened. The "nothing" seems to be a variable I don't have access to. What approach can I take to solve this?
Solution 1:[1]
You can use an 'and' where the left side is the condition and the right side is the value when the condition is True. Something like this:
<div tal:define="myvarible python: CONDITION and 'value when condition is True' or 'value when condition is False'">
</div>
Solution 2:[2]
I guess what you want is:
tal:define="certification result/h_or_e | string:blank"
If the path expression is not valid (this is like try/except), il will return the string "blank".
Note however that it will return False or None if that's the return value of h_or_e.
You can also check separately if a path exists, like this:
tal:define="path_exists exists:nocall:result/h_or_e"
The nocall prevents the path result to be executed in case it exists.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MrTango |
| Solution 2 | Georg Pfolz |
