Have you ever wanted to wrap a MODX tag in some HTML, and render it only if the value was not empty? If so, you might recognize something like this:
Well, this is okay, but there’s another way that keeps the logic in a Snippet, and the output template-able via a Chunk. (Very MODX-y way of doing it ;) Furthermore, it’s only one line of PHP!
Just tell me how to do it…
Make yourself a custom Snippet in MODX by right-clicking the “Snippets” item in the Element Tree and selecting “New Snippet”. Call it whatever you want – mine is “wrapifnotempty”. Then in the code field, paste in this one line:
if (!empty($input)) return $modx->getChunk($options, array('output' => $input));
Break It Down:
- This Snippet is meant to be used as an output modifier, so the
$inputvariable is populated with the value of whatever MODX tag you call with the output modifier, like this:
$optionsvariable holds the value from within the backticks, which in output modifier syntax is used like this:
[[*introtext:wrapifnotempty=`myChunkName`]]. That value is the first argument passed to the
$modx->getChunkmethod, which references the Chunk by name.
- The second argument to
$modx->getChunkis an array with a placeholder key, in this case ‘output’, and the value to render in that placeholder, which is
$input, the value of the input field.
In other words, take the value of this field and wrap it with this Chunk, rendering the field value in the placeholder called ‘output’. Your Chunk may contain something like:
Now, if the field is empty, nothing will render, including the wrapper. Otherwise your field value is formatted exactly the way you want. Just another handy-dandy way to use your favorite CMS :)