Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a variable is equal to zero in twig and value defined

Tags:

php

twig

This seems like a very basic question but I assure you I've run the gamut of solutions for this to work and I still haven't managed to find a solution.

The problem is this:

  1. A twig value will be set with a value of 1, 0, or null by a select box and the value will then be used to set the selected value for that box.

  2. There are two filters that are chosen - 1 for active, 0 for inactive.

  3. If no value is set and the twig value is set empty (null) the option for 0 is always selected.

The twig code in question is as follows: <option value="null">Select an Option</option> <option value="1"{% if filterStatus == 1 %} selected{% endif %}>Active</option> <option value="0"{% if filterStatus == 0 %} selected{% endif %}>Inactive</option>

Is what I expected to use. Below is one of many variations I attempted:

{% if filterStatus == 0 and not filterStatus != 'null' %}

I just can't seem to ensure the value is 0.

Also don't be fooled by the "null" value in the option value attribute. This is used in routing, but translates to a literal NULL in the system and not a string by the time it makes it to twig.

Any help is greatly appreciated.

like image 679
Ryan Rentfro Avatar asked May 26 '15 06:05

Ryan Rentfro


People also ask

How do you check variables in twig?

By setting strict_variables to false If set to false , Twig will silently ignore invalid variables (variables and or attributes/methods that do not exist) and replace them with a null value. When set to true , Twig throws an exception instead (default to false ).

Is not equal to in twig?

Twig != is a comparison operator. You can use != to compare any two things that php lets you compare, and what you get back is a boolean.


1 Answers

The way of checking for not null is:

{% if var is not null %}

But you can use the same as function:

{% if var is same as(0) %}
    {# do something %}
{% endif %}

Ref: http://twig.sensiolabs.org/doc/tests/sameas.html

like image 131
magnetik Avatar answered Sep 28 '22 05:09

magnetik