Mini-introduction to shortcodes

Mini-introduction to shortcodes

A ShortCode is basically a placeholder for some string, that might be a rendered template, or just some plain HTML string. A somewhat more complex use of shortcode is the injection of 9small) custom forms in the content area. An example creating a subscription form can be found in the 'Forms' section.

Implementing a shortcode is reeeeally simple - that's probably why it's hardly documented. Let's say we want a shortcode [Dummy] to add a bit of extra HTML into the Content area:

In your Page_Controller create a static function 'DummyHandler':

static function DummyHandler($arguments, $content) {

	// return some HTML:
	return '<h3>Replacement text</h3>';
}

Now tell SilverStripe to use the Page::DummyHandler() function everytime it encounters the [Dummy] placeholder. In your mysite/_config.php:

ShortcodeParser::get('default')->register(
	'Dummy', array('Page_Controller', 'DummyHandler')
);

That's it. Everytime you place [Dummy] in your editor, it will be replaced by '<h3>Replacement text</h3>'. Responsible for this is the ShortcodeParser class (that lives in sapphire/parsers/ShortodeParser.php), and performs a simple regexp against the content.

Excerpt from the core ShortcodeParser.php file:

The Shortcode API (new in 2.4) is a simple regex based parser that allows you to replace simple bbcode-like tags within a HTMLText or HTMLVarchar field when rendered into a template. It is inspired by and very similar to the [Wordpress implementation](http://codex.wordpress.org/Shortcode_API) of shortcodes. Examples of shortcode tags are:

[shortcode]
[shortcode /]
[shortcode parameter="value"]
[shortcode parameter="value"]Enclosed Content[/shortcode]

You can enter multiple parameters, by separating individual parameters with a space. all parameters will be stored in the $arguments array parameter in the shortcode handler, so you can access them from there. The enclosed content will be stored as a string in the shortcode handlers' $content parameter.

Note that shortcode 'tags' cannot be nested, and that parameters should be lowercase...

Comments

Het versturen van reacties is uitgeschakeld.

RSS feed voor reacties op deze pagina