Justin Blayney
Justin Blayney

Reputation: 781

twig/wordpress check if value is in array

I am testing if a value exists in an array in my twig template

<input type="hidden" name="s" value="{{ search_value }}">
  <label>
    <input type="checkbox"  
           name="cat[]" 
           value="3" 
           onchange="this.form.submit()"
           {% if 3 in cat  ? ' checked' : '' %} >
    <span>cbd</span>
  </label>
  {{ cat }}

My {{ cat }} dumps array on the page, I'm sure my problem is a silly syntax error. The error i get is

Fatal error: Uncaught Exception: Unexpected end of template. in....

if I wrap in this way I get a different error

 {% (if 3 in cat)  ? ' checked' : '' %} >
Fatal error: Uncaught Exception: A block must start with a tag name.

Upvotes: 0

Views: 419

Answers (1)

Yoshi
Yoshi

Reputation: 54659

Use a proper if:

{% if 3 in cat %}checked{% endif %}

Or a ternary (search for "The ternary operator"):

{{ 3 in cat ? ' checked' : '' }}

Or a shortened ternary:

{{ 3 in cat ? ' checked' }}

Upvotes: 5

Related Questions