将特定值传递给自定义标签

Passing specific values to custom tags

我想将特定值传递给各种自定义标签,如下所示:

<cfif someerror>
  <cfset mytag.bordercolor = "red">
</cfif>

<cf_input id="mytag">

这在某种程度上可能吗?

根据文档,您所拥有的应该可以工作 除了您忘记将变量名括在井号标签 # 之外 。试试这个:

<cf_input id="#mytag#">

关于如何将变量传递给自定义标记,需要牢记一些重要事项。 来自文档 - Passing variables to custom tags and UDFs

Passing variables to CFML tags and UDFs

When you pass a variable to a CFML custom tag as an attribute, or to a user-defined function as an argument, the following rules determine whether the custom tag or function receives its own private copy of the variable or only gets a reference to the calling page's variable:

  • Simple variables and arrays are passed as copies of the data. If your argument is an expression that contains multiple simple variables, the result of the expression evaluation is copied to the function or tag.
  • Structures, queries, and cfobject objects are passed as references to the object.
    If the tag or function gets a copy of the calling page's data, changes to the variable in the custom tag or function do not change the value of the variable on the calling page. If the variable is passed by reference, changes to the variable in the custom tag or function also change the value of the variable in the calling page.
    To pass a variable to a custom tag, you must enclose the variable name in number signs. To pass a variable to a function, do not enclose the variable name in number signs.

我不确定我是否听懂了你的问题,所以我会抛出一些可能相关的信息。

您输入的语法将起作用。

在 input.cfm 文件中,您将引用 Attributes.id。其值为 "mytag".

我建议使用 cfparam 设置默认值。

 <cfparam name="Attributes.id" type="string" default="tag">

例如。

如果你想传入 "mytag" 结构而不是字符串 "mytag" 那么你将使用以下语法:

 <cf_input id="#mytag#">

这将允许您使用 Attributes.mytag.bordercolor 获得颜色。

在这种情况下,您的 cfparam 将更像是:

 <cfparam name="Attributes.id" default="#StructNew()#">

如果你想传入字符串,但仍然从页面的变量范围中获取颜色,那么它将是这样的:

 <cfif StructKeyExists(Caller,Attributes.id) AND StructKeyExists(Caller[Attributes.id],"bordercolor")>
   <cfset Variables.bordercolor = Caller[Attributes.id].bordercolor>
 </cfif>

这是因为调用页面的变量范围在自定义标记中作为 "Caller" 范围可用。但是,我建议您在使用它时要小心,因为您正在破坏封装。如果您要访问专门传入的变量名,那 可能 没问题,但从调用者范围获取非指定变量通常不是一个好主意。