When querying multiple model types (entries, Commerce products and Commerce variants) I want to be able to detect the model type of each item as I iterate over the results array.

Ideally to avoid this sort of error:

Craft\EntryModel and its behaviors do not have a method or closure named

There doesn't seem to be a clean way of doing this but I may be wrong!

  • Are you doing this from PHP or from Twig?
    – Brad Bell
    Aug 16, 2017 at 19:27
  • From Twig, hence the confusion...
    – amogower
    Aug 16, 2017 at 22:52

1 Answer 1


Twig doesn't have a native "instanceof" check, but it'd be pretty trivial to create a simple plugin that added a Twig Extension where you can add an instanceof test.

public function getTests()
    return array(
        'instanceof' =>  new \Twig_Function_Method($this, 'isInstanceof')

public function isInstanceof($var, $instance)
    return  $var instanceof $instance;

Then from your template, you'd do something like:

{% if value is instanceof('Commerce_ProductModel') %}
  • Thanks Brad, I was hoping for a solution in Twig but this will do nicely!
    – amogower
    Aug 17, 2017 at 21:44

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.