twig的 tests 学习

文章来源:http://twig.sensiolabs.org/doc/tests/index.html

做逻辑判断的。目前支持的有

divisibleby null even odd sameas constant defined empty

divisibleby

检查是否能被整除

  1. {% if loop.index is divisibleby(3) %} 
  2.     ... 
  3. {% endif %} 
{% if loop.index is divisibleby(3) %}
    ...
{% endif %}

null

  1. {{ var is null }} 
{{ var is null }}

even

变量是否是偶数

  1. {{ var is even }} 
{{ var is even }}

odd

变量是否是奇数

  1. <PREclass=htmlname="code">{{ var is odd }}</PRE><BR> 
  2. <BR> 
  3. <P></P> 
  4. <PRE></PRE> 
  5. <P></P> 
  6. <H1><Aname=t4></A>sameas</H1> 
  7. <P>检查变量的地址是否相同</P> 
  8. <P><PREclass=htmlname="code">{% if foo.attribute is sameas(false) %} 
  9.     the foo attribute really is the ``false`` PHP value 
  10. {% endif %}</PRE><BR> 
  11. <BR> 
  12. <P></P> 
  13. <H1><Aname=t5></A>constant</H1> 
  14. <P>检查变量的值是否相同</P> 
  15. <P><PREclass=htmlname="code">{% if post.status is constant('Post::PUBLISHED') %} 
  16.     the status attribute is exactly the same as Post::PUBLISHED 
  17. {% endif %}</PRE><BR> 
  18. <BR> 
  19. <P></P> 
  20. <H1><Aname=t6></A>defined</H1> 
  21. <P>测试变量是否定义</P> 
  22. <P><PREclass=htmlname="code">{# defined works with variable names #} 
  23. {% if foo is defined %} 
  24.     ... 
  25. {% endif %} 
  26.  
  27. {# and attributes on variables names #} 
  28. {% if foo.bar is defined %} 
  29.     ... 
  30. {% endif %} 
  31.  
  32. {% if foo['bar'] is defined %} 
  33.     ... 
  34. {% endif %}</PRE><BR> 
  35. <BR> 
  36. <P></P> 
  37. <H1><Aname=t7></A>empty</H1> 
  38. <DIV>测试变量是否为空,empty的意思是:该变量已经定义,但他的值是 null false 或者是空字符串</DIV> 
  39. <DIVsizcache="1"sizset="9"><PREclass=htmlname="code">{# evaluates to true if the foo variable is null, false, or the empty string #} 
  40. {% if foo is empty %} 
  41.     ... 
  42. {% endif %}</PRE><BR> 
  43. <BR> 
  44. </DIV> 
原文地址:https://www.cnblogs.com/Kakasi/p/2881020.html