自定义CFInclude用于文件自定义

Ant*_*Tcb 3 coldfusion bluedragon coldfusion-7

我们的代码库有很多以下示例,因为我们允许根据客户的个性化需求定制很多基页.

<cfif fileExists("/custom/someFile.cfm")>
    <cfinclude template="/custom/someFile.cfm" />
<cfelse>
    <cfinclude template="someFile.cfm" />
</cfif>
Run Code Online (Sandbox Code Playgroud)

我想创建一个自定义CF标签,以此作为一个简单的模板<cf_custominclude template="someFile.cfm" />,但我遇到了自定义标签实际上是黑盒子的事实,所以他们没有拉动标签开始之前存在的局部变量,我可以引用由于标记导致的任何变量导入文件.

例如

<!--- 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. --->
Run Code Online (Sandbox Code Playgroud)

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

Nat*_*ate 5

好吧,我一直在质疑这一点,但我知道我们所有人都需要处理代码,以及让人们重构的困难.

这应该做你想要的.需要注意的一件重要事情是,您需要确保自定义标签已关闭,否则无法使用!只需使用简化的结束,就像你上面所说:

<cf_custominclude template="someFile.cfm" />
Run Code Online (Sandbox Code Playgroud)

这应该是诀窍,称之为你有它: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>
Run Code Online (Sandbox Code Playgroud)

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

<!--- Pulls in steve2 var from include --->
<cf_custominclude template="someFile.cfm" />
<cfdump var="#steve2#" /> <!--- works! --->
Run Code Online (Sandbox Code Playgroud)

  • 还应注意,关闭标记会导致它执行两次,因此如果不使用`thisTag.executionMode`,那些`cfif`块之外的任何内容都将被复制. (2认同)