Nik*_*kiC 507
根据您的具体需求:
is null检查值是否为null:
{% if var is null %}
{# do something #}
{% endif %}
Run Code Online (Sandbox Code Playgroud)is defined 检查变量是否已定义:
{% if var is not defined %}
{# do something #}
{% endif %}
Run Code Online (Sandbox Code Playgroud)此外is sameas,对两个值进行类型严格比较的测试可能对检查除null(例如false)以外的值有用:
{% if var is sameas(false) %}
{# do something %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)
lax*_*ike 123
如何在树枝中设置默认值:http://twig.sensiolabs.org/doc/filters/default.html
{{ my_var | default("my_var doesn't exist") }}
Run Code Online (Sandbox Code Playgroud)
或者,如果您不希望它在null时显示:
{{ my_var | default("") }}
Run Code Online (Sandbox Code Playgroud)
Jam*_*mol 34
没有任何假设,答案是:
{% if var is null %}
Run Code Online (Sandbox Code Playgroud)
但这只有在var确切的情况下才会成立NULL,而不是任何其他评估的值false(例如零,空字符串和空数组).此外,如果var没有定义,它将导致错误.更安全的方式是:
{% if var is not defined or var is null %}
Run Code Online (Sandbox Code Playgroud)
可以缩短为:
{% if var|default is null %}
Run Code Online (Sandbox Code Playgroud)
如果您没有为default过滤器提供参数,则它假定NULL(默认为默认值).所以最简单,最安全的方法(我知道)检查一个变量是否为空(null,false,空字符串/数组等):
{% if var|default is empty %}
Run Code Online (Sandbox Code Playgroud)
我认为你不能.这是因为如果在树枝模板中未定义(未设置)变量,则它看起来像NULL或none(以树枝形式表示).我很确定这是为了抑制模板中发生的错误访问错误.
由于Twig(===)缺乏"身份",这是你能做的最好的事情
{% if var == null %}
stuff in here
{% endif %}
Run Code Online (Sandbox Code Playgroud)
这意味着:
if ((isset($context['somethingnull']) ? $context['somethingnull'] : null) == null)
{
echo "stuff in here";
}
Run Code Online (Sandbox Code Playgroud)
其中,如果你的好你的类型杂耍,意味着的东西,如0,'',FALSE,NULL,未定义的变种也会作出这样的说法正确.
我的建议是要求在Twig中实现身份.
小智 5
//test if varibale exist
{% if var is defined %}
//todo
{% endif %}
//test if variable is not null
{% if var is not null %}
//todo
{% endif %}
Run Code Online (Sandbox Code Playgroud)
小智 5
您也可以使用一行来做到这一点:
{{ yourVariable is not defined ? "Not Assigned" : "Assigned" }}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
221290 次 |
| 最近记录: |