twig-tips

Don’t Use Twig: behaviors!

<?php
namespace modules\appmodule\behaviors;

use craft\elements\db\EntryQuery;
use craft\elements\Entry;

class Product extends \yii\base\Behavior
{
    public function getReviews(): EntryQuery
    {
        return Entry::find()
            ->section('reviews')
            ->relatedTo([
                'targetElement' => $this->owner,
                'field' => 'product',
            ]);
    }

    public function getIsActive(): bool
    {
        return $this->owner->getFieldValue('isDiscontinued') || !$this->owner->manufacturer->exists();
    }
}

You now have access to all these methods from Twig or PHP:

{% if entry.getIsActive() %}
    {% for review in entry.getReviews() %}
        {{ review.body }}
    {% endfor %}
{% endif %}