Ryan Rentfro
Ryan Rentfro

Reputation: 1662

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

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.

Upvotes: 10

Views: 20828

Answers (2)

Mahadeva Prasad
Mahadeva Prasad

Reputation: 709

Try this

{% if filterStatus == 0 and filterStatus is (not) empty %}

Upvotes: 6

magnetik
magnetik

Reputation: 4431

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

Upvotes: 17

Related Questions