Snippets are awesome. They allow for dynamic content in silly-sweet ways. Often, however, we create Snippets that reuse conditional code that we could have simply typed once. The desire for this often comes from the need to use these same conditions in several different types of Chunks, Template or Resources in different ways. This simple tutorial will show you how to write a Snippet that may be used as either a conditional Chunk or a conditional Function. This saves a lot of keystrokes and duplication of logic. Depending on circumstances, it may also improve processing and memory.
Here's a simple Snippet that will serve Conditional Chunks: (isLessThan)
<?php
// Initialize Properties
// WE'RE NOT INITIALIZING CHUNKS
$value = !empty($value)
? $value
: 50;
$limit = !empty($limit)
? $limit
: $limit;
// Check our Conditions
if ($value < $limit)
{//If we have Chunk, process it
if (!empty($yes))
$output = $modx->getChunk($yes, $scriptProperties);
// Otherwise, return Boolean True
else
$output = true;
}
// If we have Chunk, process it
elseif (!empty($no))
$output = $modx->getChunk($no, $scriptProperties);
// Otherwise, use Boolean False
else
$output = false;
// Return the Output no matter what it is.
return $output;
Simple enough... Now we just have to see it in action. First a Resource.
[[!isLessThan?
&value=`25`
&limit=`30`
&yes=`chunkOne` [[- Use any Chunk that you already have]]
&no=`chunkTwo` [[- Use any Chunk that you already have]]
&anyParamForOneOrTwo=`value` [[- Use as few or as many as you need to pass.]]
...
...
]]
If you run the resource, obviously the 'yes' Chunk will appear. But now we also have this behavior for other Snippets (saving placeholders, memory and sometimes processing).
Here's another simple Snippet:
// Call the first Snippet
$isLessThan = $modx->runSnippet('isLessThan', array('value'=>25, 'limit'=>20));
// React to the Results
if ($isLessThan)
$output = 'We hit the jackpot';
else
$output = 'Bummer, dude!';
return $output;
If you call this Snippet (notice it has no params), you'll get entirely different output than the other call. Now you've just reused a Conditional Snippet as a Function. It's a simple trick,, but often overlooked. This Tip is just a reminder that MODx is cool for much more than content.
[ed. note: fuzzicallogic last edited this post 14 years, 1 month ago.]