【问题标题】:How to define if object is equal to null in magnolia freemarker(.ftl)如何在 magnolia freemarker(.ftl) 中定义对象是否等于 null
【发布时间】:2018-02-20 16:32:01
【问题描述】:

我目前正在处理一个组件,我需要一个 if else 语句来过滤页面对象是否为空,这是我的尝试:

[#assign page = cmsfn.page(component)]
[#if page IS NULL ] // not working...
   [@cms.component content=cmsfn.asContentMap(component) editable=false/]
[/#if]

还有这个

[#assign page = cmsfn.page(component)]
[#if !page?has_content ] // not working...
   [@cms.component content=cmsfn.asContentMap(component) editable=false/]
[/#if]

我在这里要做的是,如果页面对象为 null ,则进行组件渲染,这些页面对象是 jrc 子节点,在渲染组件时这种类型的节点会弄乱模板,所以我需要过滤输出并确保页面为空,然后渲染。

有什么建议吗?请给我一个代码示例。 谢谢

【问题讨论】:

    标签: nodes freemarker jcr magnolia


    【解决方案1】:

    FreeMarker (2.x) 的模板语言有这个...怪癖,它没有null 值。因此,您不能将null 存储在变量中。当您拥有foo.bar 时,其中bar 对应于返回null 的Java getBar(),那么就模板语言而言,foo 根本不包含bar。而且,引用不存在的东西是非法的,除非您在引用表达式上应用null/missing 处理程序运算符直接(如foo.bar!'myDefault'foo.bar??)。 p>

    所以最简单的方法是避免像[#if cmsfn.page(component)??]...[/#if] 这样的赋值。但有时这是不可接受的,因为您必须再次获得page。然后,您可以使用一些可以与非默认值区分开来的默认值。假设对于page 对象?has_content 给出true(除非你使用一些奇怪的ObjectWrapper 它确实如此),一个像{}(空哈希)这样的默认值就足够了。 exp! 运算符可以用作简写,因为它还提供了 ?has_content 为 false 的默认值:

    [#assign page = cmsfn.page(component)!]
    [#if page?has_content]
       [@cms.component content=cmsfn.asContentMap(component) editable=false/]
       ... Do something with `page`, otherwise we need not use #assign.
    [#else]
       ... Don't do anything with `page`, it's that strange default object.
    [/#if]
    

    【讨论】:

      猜你喜欢
      • 2016-06-12
      • 2014-02-28
      • 2021-09-13
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2018-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多