15

How do I check what type my variable of (string, integer, boolean, array, dictionary, etc)?

1
  • 2
    Your solution may be the best one so far. It looks as if Twig has rejected adding this feature as it doesn't fall inline with the goals of Twig. github.com/fabpot/Twig/issues/595
    – Ian
    Jul 11, 2014 at 17:36

4 Answers 4

9

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 #}
1
  • Very nice, Victor!
    – carlcs
    Jul 29, 2014 at 16:37
14

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

7

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 %}
1
4

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.