Search code examples
phptwigcraftcms

How do you loop over a tag field when passing from template to a custom template tag in Craft 3?


Supposing I have a Twig template like this:

{{ craft.myPlugin.bar(entry.specialTags) }}

How can I efficiently do the following within my custom template tag?

public function bar($tags)
{
    if ($tags->contains('blah')) { // pseudo-code!
        // return something...
    }
}

Solution

  • It seems that you can loop through each of the tags of a tag field like this:

    for ($tagField->all() as $tag) {
        if ($tag->title == "blah") {
            // return something...
        }
    }
    

    Or to use something like the following to convert into a list of just tag titles:

    $tagTitles = array_map(
        function($tag) { return $tag->title; },
        $tagField->all()
    );