0

I am trying to define a function in a template, but sometimes the template is called twice. I tried

<cfscript>
if (not isdefined("tested"))    {

    string function tested(required string component) output="false"    {

        if (arguments.component CONTAINS "internal") return 'N/A';
    ....


 </cfscript>

But I still get a

enter image description here

James A Mohler
  • 11,060
  • 15
  • 46
  • 72

2 Answers2

5

I don't believe you can do what you are trying to do.

When you define a function in the code, even if you surround it by IF / ELSE, the runtime compiler is still going to parse the code for the purpose of creating the Java byte code needed to run it. So your class/function is defined twice with regard to code organization. The whole idea behind a function or component is that you move it outside of your procedural or logic code into it's own library or group of functions - that way it's easy to reuse. Sorry to be the bearer of bad news :)

Mark A Kruger
  • 7,183
  • 20
  • 21
  • 1
    Good point for suggesting organising the code better so that this sort of thing doesn't come up. It's symptomatic of poor design to have stand-alone UDFs floating around the place, as well as it is to have insufficient control of the code that results in this situation in the first place. – Adam Cameron Nov 25 '14 at 22:28
  • Adam, you are correct of course - but you need a smilin face so James knows you are not upset with him about it :) – Mark A Kruger Nov 25 '14 at 22:38
  • StackOverflow told me off for using "+ 1" in my comment, so surprised they'd let me do something so flippant as adding an emoticon. James knows what I'm like already anyhow. ;-) – Adam Cameron Nov 25 '14 at 22:40
  • Really? I've never used plus one but I'm always using smileys. I like people to think of me as smiling and forgiving them of almost any coding foible - there but for the grace of you know who go I. Actually I think I just came from there. – Mark A Kruger Nov 25 '14 at 22:43
2

You'd have to do it this way:

<cfscript>
if (!isdefined("tested")) {
    include "tested.cfm";
}
</cfscript>

And then move your tested() into tested.cfm.

Or if you're using CF11, you may try include "tested.cfm" runonce=true;

See: Can you isolate code from being seen from CF10 compiler?

Community
  • 1
  • 1
Henry
  • 32,689
  • 19
  • 120
  • 221