How do I check what type my variable of (string, integer, boolean, array, dictionary, etc)?
5 Answers
I needed this feature today, so I've put together a simple plugin, which does the job: Craft-TwigTypeTest
Example:
{% set test_var = craft.entries %}
{% if test_var is of_type('object') %}
true
{% endif %}
or
{% set test_var = craft.entries %}
{{ test_var|get_type }}
{# Outputs: object #}
To my knowledge this is not possible natively in Twig. Depending on your situation / template needs here are some useful tests
{% if foo is iterable %}
Array or object
{% if foo is same as(true) %}
Basically identical to using === in php
I recently needed to check if a variable is a number. My first idea was to use the divisibleby
test:
{# DOESN'T WORK AS EXPECTED! #}
{% if var is divisible by(1) %}
{% endif %}
Unfurtunatelly twig returns true
for every string passed to it.
But what you can do is to use regular expressions using the matches
operator in the comparison. You'll note that I double escaped the dot and the meta-character \d
, this is because of a twig bug (or put otherwise: wrong documentation of using regex here).
{# Match integer #}
{% if var matches '/^\\d+$/' %}
{% endif %}
{# Match floating point number #}
{% if var matches '/^[-+]?[0-9]*\\.?[0-9]+$/' %}
{% endif %}
-
1very nice , i didn t know u can regex in twig Commented Feb 25, 2016 at 14:07
I hit a snag for this where I needed to check if a value was a boolean type. This isn't the greatest approach, but it does work and is easy to interpret:
{% if value is same as(false) or value is same as(true) %}
Documentation: https://twig.symfony.com/doc/2.x/tests/sameas.html
In the current version of Craft/Twig (Craft 5) you can do the following:
{% if value is integer or value is float %}
...
{% endif %}