Using snippets as output filters in MODx Revo
Posted by garryn on Jan 31, 2010 | Filed under: MODx Revolution
In this blog post I aim to show you how to use snippets as custom output filters in MODx Revolution. Output filters are the updated equivalents of output widgets that are available in MODx Evolution and being able to use snippets as output filters provides a great degree of flexibility. For example, to format a date TV:
[[*createdon:strtotime:date=`%Y-%m-%d`]]
Output filters can be attached to any element, such as a TV or placeholder, and they provide a way to customize the output of that element on the page. As an example, I am going to describe how I used a snippet as an output filter to generate my tag links on this site.
The prerequisites are that there is a TV available to my blog post resource. For this blog, I created a multi-select listbox TV allowing for quick selection of my tags when creating a new blog post.
Now, to the front-end, I can easily render out my tag links by setting the default output filter for my TV to be of type Delimiter - this allows me to display a comma-separated string of my tags on the blog post. However, I wanted to facilitate a tag search option where clicking on a tag link would then display a list of all other blog posts that have been assigned that tag. For this, I need to create a custom output filter.
Each snippet used as an output filter receives a series of snippets parameters that provide the necessary data about the element being processed - here are the parameters that concern this post:
- input: The actual value of the element - if you have previous output filters defined, then this is the value after those output filters have been processed.
- options: A string that can be passed to the snippet specifying any configuration parameters that may be required. In this example, this will contain the resource ID of my tag search page.
So, onto the snippet:
if ($scriptProperties['input'] == '') return '';
$tags = explode('||', $scriptProperties['input']);
$output = array();
foreach ($tags as $tag) {
$output[] = '<a href="' . $modx->makeUrl($scriptProperties['options'], '', 'tags=' . $tag) . '">' . $tag . '</a>';
}
return implode(', ', $output);
Here, I am first checking the input value, there is no reason to continue if no tags have been selected. Then, I split out each individual tag in the comma-separated string and loop through to generate my links. Finally, the output array is imploded to return the processed output as a comma-separated string again.
To use this output filter, I simply have to attach it to my tags template variable in my resource:
[[*tags:toTagLinks=`14`]]
The ability to use snippets as output filters is another great and powerful feature of MODx Revolution. In a future blog post, I will show you how to utilize existing snippets available from the MODx repository to create the tag search page.