3

First of all, I know that the logic should be in the controller and not in the view and I keep it that way.

But in this particular situation I need to use preg_match within a ternary operation to set the css class of a div.

Example:

{% for list in lists %}
    <div class="{{ (preg_match(list.a, b))>0 ? something : else }}"...>...</div>
{% endfor %}

How can I achieve the (preg_match(list.a,b))>0 condition in twig?

Thanks in advance

JMagalhaes
  • 295
  • 2
  • 4
  • 7

3 Answers3

6

For those who came here from Google search results (like me).

There's containment operator that allows you to do something like this:

{{ 'cd' in 'abcde' }} {# returns true #}

Serge Kvashnin
  • 4,332
  • 4
  • 23
  • 37
5

You can't use preg_match() directly but there are ways to accomplish it:

  1. if your list is an entity, add a method matches(): {{ (list.matches(b)) ? something : else }}

  2. you could create a custom Twig extension function that uses preg_match() internally http://symfony.com/doc/master/cookbook/templating/twig_extension.html

Thomas Landauer
  • 7,857
  • 10
  • 47
  • 99
Michael Smith
  • 409
  • 3
  • 6
0

Expanding from Serge's comment and is the correct answer.

In my example my string is "Message Taken - 12456756". I can then use |split to convert it into an array and use |replace to get ride of white space.

{% set mt = 'Message Taken' in d.note %}
{% if mt == true %}
   {#.. you can then do something that is true#}
   {% set mt_array = d.note|split('-') %}
   {{ mt_array[0] }} | {{ mt_array[1]|replace({' ' : ''}) }}
{% endif %}

This would output my string but I now control two parts instead of 1.

Robert Saylor
  • 1,279
  • 9
  • 11