Search code examples
phptwigtwig-extension

Verify if is in array in twig template


I have a question, it's possible to make a in_array in twig template? For example I have an array call aColors with colors of one product :

Array[
  0 => "1"
  1 => "2"
]

And I have a class in Libraries folder :

class Colors{
public static $aColors = array(
    '1' => 'White',
    '2' => 'Black',
    '3' => 'Yellow',
    '4' => 'Red',
    '5' => 'Green',
    '6' => 'Blue',
);
}

Now I want to verify if the values of array with colors of product = with keys of general array with colors, And I tried in .twig :

{% for key,val in aColors %}
      {% if val in Colors::aColors %}
{% endfor %}

But not work. Exist a solution? Please help me. Can anyone help me? Thx in advance!!!


Solution

  • Twig is not intended to run any PHP code in it. It is official position of Twig developers: Twig is a template engine and the only thing it does is templating, it doesn't know anything about classes, static class properties and other PHP-only stuff. The options you have are:

    • Pass this array as a context variable, global or local, just as you usually do (preferred way).
    • Create an extension or Twig function that will access your class property internally (this goes against Twig principles, but works, though i'll use another line of my answer just to warn you not to do it).