Snippets - With includes and own controllers

When I developed https://github.com/jenstornell/kirby-bricks I found some new ways to work. It was targeting the template part where a template is a folder containing blueprint, controller, template ect.

This time I’ve figured out some new ways to work with snippets.

  • Include
  • Controller
  • Snippet

An example:

snippets/logo/snippet.php
snippets/logo/controller.php

snippets/header/header.php
snippets/header/controller.php
snippets/header/snippet.php
snippets/header/style.css

Include

snippets/header/header.php

In for example the Patterns plugin the matching folder name as file is the snippet.

In this setup it’s a bit different. It’s used as an include. It’s included before the template engine is loaded (not when the snippet is called). It can be good to have for including classes that are snippet specific. You can also include other files from it.

include 'my-custom-class.php';

class SomeClass {
}

Controller

snippets/header/controller.php

Templates can have controllers. Because I work very modular I tought it would be nice to have controllers for snippets as well.

It can be used to make values available for this snippet but not for any other snippets. If you send data with the snippet you can use that in the controller as well.

Call header snippet from the main snippet

snippets/main/snippet.php

Include some data as well:

snippet('header', ['data_from_snippet' => 350]);

Add a header controller

snippets/header/controller.php

Add something to the data and return it into price.

<?php
return function($site, $pages, $page, $data) {
  $data['data_from_snippet'] = $data['data_from_snippet'] . ' USD';
  return array(
    'price' => $data['data_from_snippet']
  );
};

Get the data in the header snippet

snippets/header/snippet.php

echo $price;

It will output 350 USD.

Snippet

snippets/header/snippet.php

This is the snippet html file.

Plugin in the making

I already have a plugin for it. It’s done but require some testing. But all of the above seems to work as I expected.

What do you think?

2 Likes