2011-12-05 10 views
95

Wygląda na to, że mam problem z instrukcją gałązki.gałązka: JEŻELI z wieloma warunkami

{%if fields | length > 0 || trans_fields | length > 0 -%} 

Błąd jest:

Unexpected token "punctuation" of value "|" ("name" expected) in 

Nie mogę zrozumieć, dlaczego to nie działa, to tak jakby gałązka zaginął ze wszystkimi rurami.

Próbowałem to:

{% set count1 = fields | length %} 
{% set count2 = trans_fields | length %} 
{%if count1 > 0 || count2 > 0 -%} 

ale jeśli też nie.

Potem próbowałem to:

{% set count1 = fields | length > 0 %} 
{% set count2 = trans_fields | length > 0 %} 
{%if count1 || count2 -%} 

i nadal nie działa, za każdym razem ten sam błąd ...

więc ... że doprowadzi mnie do naprawdę proste pytanie: czy wsparcie Gałązka wiele warunków IF?

Odpowiedz

229

Jeśli dobrze pamiętam Twig nie obsługuje operatorów || i &&, ale wymaga odpowiednio użycia or i and. Użyłbym też nawiasów, aby wyraźniej objaśnić te dwa stwierdzenia, chociaż nie jest to technicznie wymóg.

{%if (fields | length > 0) or (trans_fields | length > 0) %} 

Ekspresja

Expressions can be used in {% blocks %} and ${ expressions }. 

Operator Description 
==   Does the left expression equal the right expression? 
+   Convert both arguments into a number and add them. 
-   Convert both arguments into a number and substract them. 
*   Convert both arguments into a number and multiply them. 
/   Convert both arguments into a number and divide them. 
%   Convert both arguments into a number and calculate the rest of the integer division. 
~   Convert both arguments into a string and concatenate them. 
or   True if the left or the right expression is true. 
and   True if the left and the right expression is true. 
not   Negate the expression. 

Dla bardziej złożonych operacji, może być najlepiej owinąć poszczególne wyrażenia w nawiasach, aby uniknąć nieporozumień:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %} 
+13

I oczywiście nie miał szans na znalezienie że wspaniały i oszczędzający czas stolik, patrząc na dokumentację IF: http://twig.sensiolabs.org/doc/tags/if.html Dziękujemy za rozwiązanie! – FMaz008

+5

Zwykle używają wiki na githubie, aby dokładniej dokumentować swój kod. Ten stół pochodzi z [here] (https://github.com/vito/chyrp/wiki/Twig-Reference) –

+14

Również operatorzy rozróżniają wielkość liter. LUB nie działa. – Acyra

Powiązane problemy