Intershop:检查 .isml 模板中是否为空

Intershop: checking for not null in .isml template

我没有找到用于测试 ISML 模板代码中值是否存在的函数。有 'isDefined' 但没有 'isNull'。

isDefined returns 对空值为真:

      <isset name="woot" value="" scope="request">

       <isif condition="#isDefined(woot)#">
           <h1>woot</h1>
       </isif>

目前我正在使用:

 <isif condition="#woot EQ null#">

 <isif condition="#woot EQ ''#">

我不知道这是否适用于布尔值。

isDefined 是检查空值的方式。在 AbstractTemplate 中,您调用了 isDefined(Object anObject) 方法。检查已编译的 jsp 和 java 版本的 isml 模板。

在抽象模板中

public Boolean isDefined(Object anObject){
    ...
    return anObject != null ? Boolean.TRUE : Boolean.FALSE;
}

您示例中的代码有点误导,它实际上并未测试空引用。忍耐一下。

第一个声明:

<isset name="woot" value="" scope="request">

编译为:

Object temp_obj = (""); 
getPipelineDictionary().put("woot", temp_obj);

这只是将 woot 变量设置为空字符串。如果您将以下脚本添加到您的 isml 中,您会发现它确实不是空值。

免责声明:请勿在生产代码中使用 scriptlet,这仅用于演示一个观点

<%
    Object woot = getPipelineDictionary().get("woot");
    out.print(woot == null); //print false
%>

第二行:

<isif condition="#isDefined(woot)#">

评估变量是否存在并且确实存在。它有一个空字符串作为值,而不是像你想象的那样为 null。

那么这里会发生什么?

<isif condition="#woot EQ null#">

查看编译版本:

context.getFormattedValue(getObject("woot"),null).equals(context.getFormattedValue(getObject("null"),null))

context.getFormattedValue(getObject("null"),null) 是这里的重要部分。它试图检索名为 null 的变量,它不存在,所以 returns null。然后 getFormattedValue 方法 returns 空参数的空字符串(参见 TemplateExecutionConfig::getFormattedValue)。然后整个语句评估为真。不是因为 woot 为空,而是因为您将它与不存在的变量进行比较,所以您无意中评估了两个空字符串。此行为与 EQ 运算符一致,因为它用于 compare strings.

如果你也使用这个语句,你会得到相同的结果。

<isif condition="#woot EQ iDontExistButImAlsoNotNull#"> //true

第三条语句将 woot 变量与空字符串值进行比较,returns 为真。

<isif condition="#woot EQ ''#">

编译版本:

context.getFormattedValue(getObject("woot"),null).equals(context.getFormattedValue("",null))

所以真正的问题是 woot 没有字面值 null。见以下代码:

<isset name="foo" value="#IDontExitPrettySureAboutThat#" scope="request">
<%
    Object foo = getPipelineDictionary().get("foo");
    out.print("foo is null? ");
    out.print(foo == null);
    //prints : foo is null? true
%>
<isif condition="#isDefined(foo)#">
    <h1>foo1</h1> //is never printed
</isif>

我在滥用 IDontExitPrettySureAboutThat 不存在的事实来将空值设置为 foo。 isDefined 然后开始像您期望的那样工作。直到有人将我的变量初始化为 null 以外的值。

不过,我不提倡您使用这种方法。我认为最好的建议是不要使用 null 来表示缺失值或无效状态。 thread 详细介绍了该主题。