【问题标题】:coldfusion ignore undefined variablesColdfusion 忽略未定义的变量
【发布时间】:2011-01-06 21:01:27
【问题描述】:

如果我使用

<cfoutput>#somevariable#</cfoutput>

并且somevariable 未定义我收到错误,如何防止错误发生? 有没有一种简单的方法来实现不需要一堆额外行的条件?

【问题讨论】:

    标签: coldfusion


    【解决方案1】:
    <cfparam name="somevariable" default="" />
    

    如果您使用的是 cf 9,则可以使用三元运算,但 cfparam 更“最佳实践”。

    #isDefined("somevariable") ? somevariable : 'default string'#
    

    【讨论】:

    • 如果你要使用三元运算符,我推荐structkeyexists( scope, "somevariable" ) 而不是isdefined。仅搜索您希望定义变量的范围会更快,并且它可以防止 CF 从不同的范围检索变量。如果您确实使用isdefined,至少为范围提供变量(OP 也应该这样做)。
    【解决方案2】:

    你可以测试变量

    <cfoutput>
        <cfif isDefined("somevariable")>
            #somevariable#
        <cfelse>
            handle default scenario here
        </cfif>
    </cfoutput>
    

    或者你可以使用内联条件

    <cfoutput>
        #IIF(isDefined("somevariable"),de(somevariable),de(""))#
    </cfoutput>
    

    【讨论】:

      猜你喜欢
      • 2011-12-13
      • 1970-01-01
      • 2022-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多