View Tag Library Tip: Inserting Scripts
We all work with slinging script fragments all over the place in our view layer. I'm sure you have code that looks a lot like this everywhere:
<cfsavecontent variable="variables.js">
<script type="text/javascript">
Event.observe(window, 'load', loadAccordions, false);
function loadAccordions() {
var verticalAccordion = new accordion('vertical_accordion');
}
</script>
</cfsavecontent>
<cfset addHTMLHeadElement(variables.js) />
We set some come into a variable via cfsaveconent and then sling it into the HTML head via addHTMLHeadElement() which wraps cfhtmlhead ultimately. In Mach-II, you need to use this method if you want caching to observe and later replay elements you added to the head. Ugh, that's a lot of useless code. It would be helped if cfhtmlhead supported body content (OpenBD does BTW) instead of just string data in an attribute. Enter the HTMLHelperProperty and the nifty view custom tag library in Mach-II 1.8:
<cfimport prefix="view" taglib="/MachII/customtags/view" />
<view:script>
Event.observe(window, 'load', loadAccordions, false);
function loadAccordions() {
var verticalAccordion = new accordion('vertical_accordion');
}
</view:script>
Wow, by default the view:script tag saves the content and inserts it into the head for you! If you wanted it inline, then you just add outputType="inline" as an attribute or if you are on OpenBD you can use "body" to insert it at the bottom of the HTML body element. Best thing of all is that it automatically uses addHTMLHeadElement() behind the scenes for you -- so your code is Mach-II cachable by proxy. So be sure to check out our lengthy documentation on the view library and HTML helper -- they do a lot of stuff other than what I've shown in this example.
