我在Coldfusion 2018中使用会话变量,并且试图弄清楚如何以设置if语句的方式添加变量。
<cfif isDefined("session")
and structKeyExists(session, 'checkout')
and structKeyExists(session.checkout, 'info')
and structKeyExists(session.checkout.info, 'andor_1') >
<cfif session.checkout.info.andor_1 eq "And">
<strong>- All signatures are required.</strong>
</cfif>
</cfif>
or
<cfif isDefined("session")
and structKeyExists(session, 'checkout')
and structKeyExists(session.checkout, 'info')
and structKeyExists(session.checkout.info, 'bandor_1') >
<cfif session.checkout.info.bandor_1 eq "And">
<strong>- All signatures are required.</strong>
</cfif>
</cfif>
if语句几乎是相同的andor_1
或bandor_1
,但是可能并不总是存在任何一个,这就是为什么我使用isDefined的原因。
我尝试使用||
和or
。
<cfif isDefined("session")
and structKeyExists(session, 'checkout')
and structKeyExists(session.checkout, 'info')
and structKeyExists(session.checkout.info, 'andor_1')
|| isDefined("session")
and structKeyExists(session, 'checkout')
and structKeyExists(session.checkout, 'info')
and structKeyExists(session.checkout.info, 'bandor_1')>
<cfif session.checkout.info.andor_1 eq "And" || session.checkout.info.bandor_1 eq "And">
<strong>- All signatures are required.</strong>
</cfif>
</cfif>
将这些cfifs
组合在一起的任何帮助将不胜感激。
答案 0 :(得分:3)
相对于||,CF中正确的方法是'OR'。
但是,在第一个示例中,您已将“ OR”放置在IF语句之外。试试这个:
<cfif isDefined("session") AND structKeyExists(session, 'checkout') AND structKeyExists(session.checkout, 'info')
AND (
(structKeyExists(session.checkout.info, 'andor_1') AND session.checkout.info.andor_1 eq "And")
OR
(structKeyExists(session.checkout.info, 'bandor_1') AND session.checkout.info.bandor_1 eq "And")
)>
<strong>- All signatures are required.</strong>
</cfif>
答案 1 :(得分:3)
如果使用的是CF2016,则可以使用安全导航操作符或?.
(https://www.adobe.com/devnet/coldfusion/articles/language-enhancements-cf-2016.html)。而且,您还应该开始将cfscript用于此类逻辑事务。
<cfscript>
// Setup my struct. Session is a struct. I renamed it for my example since it's a special word.
s = {
checkout : {
info : {
andor_1 : "And" ,
bndor_1 : "And"
}
}
} ;
//writeDump(session);
// If CF2016+ Safe Navigation Operator To The Rescue!
if( s?.checkout?.info?.andor_1 == "And" || s?.checkout?.info?.bndor_1 == "And" ) {
writeOutput("<strong>- All signatures are required.</strong>");
}
</cfscript>
https://trycf.com/gist/a82b8466c427fb40b53bbc506e4d419d/lucee5?theme=monokai
答案 2 :(得分:2)
另一种选择(尽管性能不如使用structKeyExists()
。
<cfif isDefined("session.checkout.info.andor_1") AND session.checkout.info.andor_1 eq "And"
OR isDefined("session.checkout.info.bandor_1") AND session.checkout.info.andor_1 eq "And">
<strong>- All signatures are required.</strong>
</cfif>
需要研究的是设置一些默认值,以便您无需运行isDefined
或structKeyExists
检查。这样做有可能清理您的代码并使其更具可读性。
当然,在某些情况下或某些情况下,它们是必要的(例如,使用API的响应)。