3

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

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

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

4

1 回答 1

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! --->
于 2018-12-18T20:40:37.163 回答