How to reuse a function in multiple templates?

This is a follow up question to this one.

I have a function to build a pages collection from a structured field which is like:

    $elements = $page->elements()->toStructure();
    $parent = $site->index()->filterBy('template', $type)->first()->parent();
    $cards = new Pages();
    foreach($elements as $element) {
      $cards->add($parent->find($element->uid()));
    }

How can i use this function in multiple templates and return $cards to the template?

Well, the problem is that this is not a function but a piece of code :wink:.

Wrap it in a function (in a plugin file) that accepts some parameters, then you can reuse it anywhere.

// use as many parameters as needed
function createCards($param1, $param2) {
  // define $cards
  return $cards;
}

Super clean as usual with Kiki! Thank you!