I’m sure the avid programmers amongst us will have applied this procedure before but this tip may fire off some creative neurons here and there. I certainly have used it and I just came accross it again in relation to
this question.
Problem:
You want to use a TV to include something in your documents but there’s no appropriate widget to format the output.
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.
Solution: Create widgets using snippets.
This is actually remarkably simple. The steps you need to follow are these:
1. Create your TV and leave the output widget empty.
2. Create a snippet which fetches the output of the TV you created and which formats the output. Assign it to a template.
3. In the template add a call to your snippet, where you would normally have placed the TV tag.
For the first example you could do something like this.
1. Create the TV with these properties
Variable name: sidebarTV
Caption: Sidebar content
Input Type: Rich Text
Widget: none
2. Create the snippet "sidebarWidget"
<?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
return '<div class="sidebarContent">'.$tvOutput.'</div>';
}
return '';
?>
3. Add snippet call to template...
<!-- Lot's of (x)html -->
<div id="leftColumn">
[!sideBarWidget!]
</div>
<div id="contentColumn">
[*content*]
</div>
<!-- more (x)html -->
That’s it...
For the stylesheet example have a look at
this snippet in the repository.