自定义CFInclude用于文件自定义



我们的代码库有很多下面的例子,因为我们允许根据客户的个人需求定制我们的许多基本页面。

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

我想创建一个自定义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. --->

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

好吧,我完全质疑这样做,但我知道我们都会在必须处理的时候收到代码,以及让人们重构的困难。

这应该是你想要的。需要注意的一点是,您需要确保您的自定义标记有一个结束符,否则它将不起作用!只需使用简化的结束语,就像上面一样:

<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! --->

最新更新