Easier html for kirbytext custom tags

Writing html into vars inside a kirby tag definition always felt a bit wrong. I thought you could use the tagname.php file to define and prepare variables and then use a snippet to render the html.

site/tags/tagname.php:

<?php

kirbytext::$tags['tagname'] = array(
  'attr' => array(
    'class'
  ),
  'html' => function($tag) {

    $vars = array(
          'tagname' => $tag->attr('tagname');
          'class' => $tag->attr('class');
        );

        $html = snippet('block-tagname', $vars, true);
        return $html;
  }
);

?>

(I like to namespace my snippets, block-something is for blocks of content that can be embedded on a page, another post for that later perhaps)

site/snippets/block-tagname.php:

<div class="<?php echo $class ?>">
  <?php echo $tagname ?>
</div>

There are only two oddities I’ve found.

The snippet needs to output something that the markdown parser recognizes as html and not text. I had to wrap an iframe inside a figure so it wouldn’t get encoded.

Also, remember to add that last true parameter when calling the snippet, so it’ll output its html into the variable. It will work without it too, but then it seems to always render the snippet as the first thing on the template and not in the place where it was invoked.

$html = snippet('block-tagname', $vars, true);

I’ve made user cards, maps and nav tags like this, so my users can use them mixed in with content. I’ll post them when I’ve had a chance to clean up the code a little. :smile:

1 Like

I use Kirby brick. Tried that?

Hmm, I’m familiar with brick yes. To entertain the thought, here’s a figure with brick and snippet. (Example from kirby brick docs)

Brick:

$figure = brick('figure');
$figure->append(function() {
  return brick('img')->attr('src', $url);
});
$figure->append(function() {
  return brick('figcaption', $caption);
});
echo $figure;

Snippet

<figure>
  <img src="<?php echo $url ?>">
  <figcaption><?php echo $caption ?></figcaption>
</figure>

Both have their place, but I mostly prefer writing plain html because that’s what I’m familiar with.