I'm creating a custom twig filter in Craft 3 and am struggling with a really simple thing.

{{ entry.backgroundImage.one() | filter }}

In my filter, I would like to validate that I am being passed an asset.

if (!$asset instanceof Asset)
    return false;

What should I be checking the object against? Asset or something different?

2 Answers 2


Actually, you had your code just right imo:

use craft\elements\Asset;


if (!$asset instanceof Asset) {
    return false;
  • looks like I forgot use craft\elements\Asset; which would have made the original code work. Thanks!
    – kisonay
    Jul 22, 2018 at 20:41
  • I think doing it this way is a good bit cleaner Jul 23, 2018 at 0:50
  • I actually agree that this is probably the cleaner solution. In comparing get_class and instanceof, a useful detail to know is that instanceof will also return true for a class extending the class you're testing against (i.e. your conditional will evaluate to true if you pass it an object w/ a class extending Asset, which may or may not be what you want), where get_class($object) === 'SomeClass' will only evaluate to true if the object actually has that particular class. In this case, I'm fairly positive it doesn't matter and both approaches will work. Jul 23, 2018 at 8:38
  • Also, instead of hard coding the full, namespaced classname, it's also possible to do use craft\elements\Asset; ... if (\get_class($asset) === Asset::class) { ... of course :) Jul 23, 2018 at 8:39
  • That is a great callout @MatsMikkelRummelhoff, great to know that this will also acknowledge exertions. In light of this, I've mad this the correct answer.
    – kisonay
    Jul 23, 2018 at 11:36

Assuming you're using Craft 3, this should work:

if (\get_class($asset) !== 'craft\elements\Asset) {
    return false;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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