Snippets for plugins


#1

Snippets for templates are awesome. In some cases snippets can be needed for plugins as well. Maybe we don’t want to mix template snippets with plugin snippets. Instead we keep the plugin snippets in the plugin folder.

Snippets for plugins - Solution

Very simple, but powerful, based on the snippet function in the Kirby core. Change your function name to something unique.

This goes into your plugin file site/plugins/my_plugin/my_plugin.php or any other file called by the plugin:

function pluginSnippet( $file, $data = array(), $return = false ) {
	$plugin = 'my_plugin';
	$folder = 'snippets';
	if( is_object( $data ) ) $data = array( 'item' => $data );
	return tpl::load( kirby()->roots()->plugins() . DS . $plugin . DS . $folder . DS . $file . '.php', $data, $return );
}

echo pluginSnippet( 'test', array('testing' => 'Hoho'), true );

Snippet

This code goes into the site/plugins/my_plugin/snippets/test.php:

<h1><?php echo $testing; ?></h1>

The output would be:

 <h1>Hoho</h1>