Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a block of code in a custom tag only run the first time the tag is called?

I'm creating a set of ColdFusion custom tags designed to make reusing certain layout elements easy. I'll be using them in a manner similar to the following:

<cfimport prefix="layout" taglib="commonfunctions/layouttags">

<layout:fadingbox>
    This text will fade in and out
</layout:fadingbox>
<layout:stockticker>
    This text will scroll across the screen
</layout>

In order for the code these custom tags generates to work, a JavaScript file needs to be linked into the page like so:

<script src="commonfunctions/layouttags/enablingscript.js" type="text/javascript"></script>

I'd prefer to include the script from inside the custom tags, instead of making the user include it himself. The issue is that the JavaScript file should only be included once per page. After the first time one of these custom tags is used, I'd like subsequent calls to the same tag on the same page to avoid repeating the <script> tag. It's occurred to me that I could do something like this:

<cfif NOT isDefined("Caller.LayoutTagInitialized")>
    <script src="commonfunctions/layouttags/enablingscript.js" type="text/javascript"></script>
</cfif>
<cfset Caller.LayoutTagInitialized = 1>

...but it seems inelegant.

I wonder, is there a better way?

How would you implement this?

Edit - Clarification:

In case what I wrote above didn't make sense, here's a more detailed example:

If I have a custom tag like this:

<cfif ThisTag.ExecutionMode EQ "start">
    <script src="commonfunctions/layouttags/enablingscript.js" type="text/javascript"></script>
    <div class="mytag">
<cfelse>
    </div>
</cfif>

...and I have CFML markup calling the tag like like this:

<layout:mytag>
    One
</layout:mytag>
<layout:mytag>
    Two
</layout:mytag>
<layout:mytag>
    Three
</layout:mytag>

...I want HTML like the following to be generated:

<!-- Script included only the first time the tag is called -->
<script src="commonfunctions/layouttags/enablingscript.js" type="text/javascript"></script>
<div class="mytag">
    One
</div>
<!-- No <script> tag on the second call -->
<div class="mytag">
    Two
</div>
<!-- No <script> tag on the third call -->
<div class="mytag">
    Three
</div>
like image 480
Joshua Carmody Avatar asked Feb 28 '23 20:02

Joshua Carmody


1 Answers

Use the Request scope.

like image 182
Peter Boughton Avatar answered Apr 08 '23 17:04

Peter Boughton