Adding TV Widgets without hacking the core
From MODx Wiki
You want to use a Template Variable (TV) to include content in your documents but there's no appropriate widget to format the output.
Let's say, for instance you want to include some content from a RTE TV in a sidebar inside a DIV block, but if the TV is empty the DIV block should not be in the output either. Or you want to be able to add extra stylesheets into a document by making a selection in a TV (see Resources).
Solution: Create widgets using snippets.
This is actually remarkably simple. The steps you need to follow are these:
- Create your TV and leave the output widget empty.
- Assign the TV to the template of your choice.
- Create a snippet that gets the output of the TV you created and format the output.
- In the template add a call to your snippet, where you would normally have placed the TV tag.
Contents |
Create the TV
Create a TV with the following properties
- Variable name: sidebarTV
- Caption: Sidebar content
- Input Type: Rich Text
- Widget: none
Create a snippet
Create a snippet named "sidebarWidget" and add the following code.
<?php // sidebarWidget snippet // parameters: // &tvname - Set the TV name to be used, defaults to sidebarTV $TVname = isset($tv)?$tv:'sidebarTV'; // fetch the output array of the TV if( $TVarray = $modx->getTemplateVarOutput(array($TVname)) ){ #TV output is in index [$TVname][1] $tvOutput = $TVarray[$TVname][1]; if(empty($tvOutput)) return ''; //bail out if no value // Here is where we can start customizing the output. // For now, just return the TV output in a <div> container return '<div class="sidebarContent">'.$tvOutput.'</div>'; } return ''; ?>
Add snippet call to template
Instead of using the [* *] syntax for the TV, we will use the un-cached snippet [! !] syntax...
<!-- Lot's of (x)html --> <div id="leftColumn"> [!sideBarWidget!] </div> <div id="contentColumn"> [*content*] </div> <!-- more (x)html -->
Conclusion
That's it!
The Snippet does all the formatting, and you still are able to use TVs in your documents.
Resources
- Have a look at addCSSWidget for another example.
