自定义CFInclude用于文件自定义

时间:2018-12-18 16:01:47

标签: coldfusion coldfusion-7 bluedragon

我们的代码库包含大量以下示例,因为我们允许将许多基础页面定制为满足客户的个性化需求。

<cfif fileExists("/custom/someFile.cfm")>
    <cfinclude template="/custom/someFile.cfm" />
<cfelse>
    <cfinclude template="someFile.cfm" />
</cfif>

我想创建一个自定义CF标签来将其简化为简单的<cf_custominclude template="someFile.cfm" />,但是我遇到了一个事实,即自定义标签实际上是黑匣子,因此它们不会提取之前存在的局部变量。标签的开头,并且导入文件时我无法引用由于标签而创建的任何变量。

E.G。     

<!--- This is able to use someVar --->
<!--- Pulls in some variable named "steve" --->
<cfinclude template="someFile.cfm" />
<cfdump var="#steve#" /> <!--- This is valid, however... --->

<!--- someVar is undefined for this --->
<!--- Pulls in steve2 --->
<cf_custominclude template="someFile.cfm" />
<cfdump var="#steve2#" /> <!--- This isn't valid as steve2 is undefined. --->

有没有解决的办法,还是应该利用其他语言功能来实现我的目标?

1 个答案:

答案 0 :(得分:5)

好吧,我完全质疑这样做,但我知道有时我们都需要处理代码,而要让人们进行重构也很困难。

这应该做您想要的。需要注意的重要一件事是,您将需要确保自定义标签已关闭或无法使用!只需使用简化的结束语,就像您在上面看到的那样:

<cf_custominclude template="someFile.cfm" />

这应该可以解决问题,称它为拥有:custominclude.cfm

<!--- executes at start of tag --->
<cfif thisTag.executionMode eq 'Start'>
    <!--- store a list of keys we don't want to copy, prior to including template --->
    <cfset thisTag.currentKeys = structKeyList(variables)>
    <!--- control var to see if we even should bother copying scopes --->
    <cfset thisTag.includedTemplate = false>
    <!--- standard include here --->
    <cfif fileExists(expandPath(attributes.template))>
        <cfinclude template="#attributes.template#">
        <!--- set control var / flag to copy scopes at close of tag --->
        <cfset thisTag.includedTemplate = true>
    </cfif>
 </cfif>
 <!--- executes at closing of tag --->
 <cfif thisTag.executionMode eq 'End'>
    <!--- if control var / flag set to copy scopes --->
    <cfif thisTag.includedTemplate>
        <!--- only copy vars created in the included page --->
        <cfloop list="#structKeyList(variables)#" index="var">
            <cfif not listFindNoCase(thisTag.currentKeys, var)>
                <!--- copy from include into caller scope --->
                <cfset caller[var] = variables[var]>
            </cfif>
        </cfloop>
    </cfif>
 </cfif>

我测试了它,它工作正常,嵌套也应该工作正常。祝你好运!

<!--- Pulls in steve2 var from include --->
<cf_custominclude template="someFile.cfm" />
<cfdump var="#steve2#" /> <!--- works! --->