Include snippets in Kirbytext using a Kirbytext filter

I had some issues with using snippets inside of a custom Kirbytag because of the order how Kirby parse content.

With the help of @lukasbestle I found a good solution with a custom Post Filter instead of a custom Kirbytag:

<? kirbytext::$post[] = function($kirbytext, $text) {

    // searching for fields with the name mytag and 1 parameter for the uid of the module, example: (mytag:my-module)
    $text = preg_replace_callback('!\(mytag:(.*?)\)!is', function($matches) use($kirbytext) {

    $searchkey = trim($matches[1]);

    // $kirbytext has a reference to the field and the field has a reference to the page
    $module = $kirbytext->field->page->children()->findBy('uid', $searchkey);

    $html = snippet('components/mymodule', array('title' => $module->title(), 'text' => $module->text()->kirbytext()), true);

    return $html;

    }, $text);

  return $text;
};
3 Likes