使用ColdFusion自定义标记的奇怪结果

The*_*Man 1 coldfusion

我创建了一个简单的自定义标记,它接受一个字符串,用" - "替换空格,用"和"替换查询字符串(我不想要%20等).

无论如何,它工作正常,但我的自定义标签正在创建一个空间,如下所示:

qsEncode.cfm :(自定义标签)

<cfparam name="attributes.string" type="string" default="">

<cfset whitespace = Replace(attributes.string," ","-","all")>
<cfset ampersand =  Replace(whitespace,"&","and","all")>

<cfoutput>#ampersand#</cfoutput>
Run Code Online (Sandbox Code Playgroud)

标签的实现:

<a href="?Page=<cf_qsEncode string="#getCategory.Name#">">#getCategory.Name#</a>
Run Code Online (Sandbox Code Playgroud)

最后的输出是在标签之前创建一个空格:

somepage.cfm?Page=%20Finance-and-Taxes
Run Code Online (Sandbox Code Playgroud)

我的自定义标记没有被传递给前面有空格的字符串(即使它被" - "字符替换)所以我不明白为什么标签创建空格.

注意:我确实知道我可以?Page=在我的自定义标签中包含哪个可以修复它,但我仍然很好奇为什么会发生这种情况.

Ken*_*ler 6

使用以下内容可能会修复额外空间的具体问题:

<cfsetting enablecfoutputonly="true">
Run Code Online (Sandbox Code Playgroud)

作为自定义标记内的第一个内容(并在结尾处将其设置为"false").

但是,我强烈建议使用实际功能替换自定义标签的功能 - 内联或(最好)在cfc内.无论哪种方式,你想要这样的东西:

<cffunction name="qsEncode" output="false" returntype="string">
  <cfargument name="str" type="string" required="true">
  <cfset var whitespace = Replace(arguments.str," ","-","all")>
  <cfset var ampersand = Replace(whitespace,"&","and","all")> 
  <cfreturn ampersand>
</cffunction>
Run Code Online (Sandbox Code Playgroud)

那你就得:

<a href="?Page=#qsEncode(getCategory.Name)#">#getCategory.Name#</a>
Run Code Online (Sandbox Code Playgroud)

对于不维护状态的这类实用程序函数,快速解决方案(抛开关于单例智慧的论据)是设置实用程序cfc,并将其作为单例存储在应用程序范围中.utility.cfconApplicationStart你的处理程序中实例化Application.cfc.然后,在整个应用程序中,您可以执行以下操作:

application.utility.qsEncode('this');
application.utility.someOtherFunction('that');
application.utility.yetAnotherStringMangler('theother');    
Run Code Online (Sandbox Code Playgroud)