Skip to content

snippets

Harmen Janssen edited this page Feb 26, 2016 · 3 revisions

Snippets

Snippets are an unstructured set of fragments of text, an image or a video, or a combination of all of those.

Rendering

To render a snippet you should use:

echo $this->snippet('snippetIdentifier');

You can also specify which partial to use, and pass additional arguments to it:

$my_params = array('foo' => 123, 'bar' => 456);
echo $this->snippet('snippetName', 'partials/foobar.phtml', $my_params);

To get a specific field without rendering you should use:

echo $this->snippet()->getField('snippetName', 'snippetField');

Creating snippets

A snippet template JSON file is available in Garp (/application/modules/g/models/config/Snippet.json). You can copy this if you want to spawn the model.

The preferred way of adding snippets is configuring them in application/configs/snippets.ini:

snippets.my_identifier.has_text = 1
snippets.my_identifier.text = "My content"

Note that you can specify as much or as little columns as you'd like. Also note that underscores in identifiers will be replaced by spaces in the database.

You can now insert them in the database using Golem:

g snippet create

Overwrite existing snippets using

g snippet create --overwrite

Variables in snippets

A conventional method of interpolating runtime variables in snippets is the following:

// snippet = "Welcome %USERNAME%, have a %TYPE_OF_DAY% day!"
echo $this->snippet('welcome message', null, array(
  'variables' => array(
    'USERNAME' => 'Henk',
    'TYPE_OF_DAY' => 'nice'
  )
)); // renders "Welcome Henk, have a nice day!"

If the snippet contains the substring "%USERNAME%", it will be replaced with "Henk" at runtime.
It's good practice to alert admins of possible variables by filling the variables column.

For instance, the above snippet would be configured in snippets.ini like this:

snippets.welcome_message.has_text = 1
snippets.welcome_message.variables = "USERNAME,TYPE_OF_DAY"
snippets.welcome_message.text = "Welcome %USERNAME%, have %TYPE_OF_DAY% day!"

Advanced options

You can pass the following parameters to $this->snippet()->render:

  • headerTag (defaults to <h3>)
  • headerClass
  • variables
  • textWrapperTag (if omitted will render text without a wrapper)
  • textWrapperClass
  • scalingTemplate, required when rendering snippets where has_image is true.
  • linkify, wether to auto-link URLs (defaults to TRUE)
  • bodyClass, only for snippets where has_html is true.
Clone this wiki locally