sightly var 和调用 sling model 的 getter 有什么区别?

What is the difference between sightly var and calling of sling model's getter?

有什么区别:

<div data-sly-test.backgroundVideo="${hero.backgroundVideo}" >
    Background video URL:
        <a href="${backgroundVideo}.html" target="_blank">
            ${backgroundVideo}
        </a>
</div>

和:

<div data-sly-test="${hero.backgroundVideo}" >
    Background video URL:
        <a href="${hero.backgroundVideo}.html" target="_blank">
            ${hero.backgroundVideo}
        </a>
</div>

哪种解决方案更有效?使用视觉变量或调用 getter?

如您所见,不同之处在于 ${hero.backgroundVideo} 的计算结果缓存在一个变量中。这对性能有一些影响,因为它消除了进行一些反思以找到调用 hero 的正确方法的需要;如果调用的方法很昂贵(JCR 查找、远程调用...),影响可能会更大

Sightly,就像任何其他类似领域的编程语言一样,对变量的使用没有强制要求。一个简单的比较是将代码转换为等效的 Java 例程,然后查看优化和性能效果(理论上)。

为了简单起见,让我们按如下方式制作您的 POJO class:

class Hero {

    public string getBackgroundVideo() {
        //Some model logic
    }

}

现在,考虑第一个代码片段:

<div data-sly-test.backgroundVideo="${hero.backgroundVideo}" >
     Background video URL:
        <a href="${backgroundVideo}.html" target="_blank">
        ${backgroundVideo}
        </a>
</div>

这只会执行一次 getBackgroundVideo() 并将其存储在变量中以供重用。

或者,对于第二个代码片段:

<div data-sly-test="${hero.backgroundVideo}" >
    Background video URL:
    <a href="${hero.backgroundVideo}.html" target="_blank">
        ${hero.backgroundVideo}
    </a>
</div>

getBackgroundVideo()会被执行3次。

So, on the surface this may look like a 1:3 difference in execution and look really costly specially if there is a complex code logic involved in the getBackgroundVideo() function. This is true and you should avoid this approach by trying to cache the output of complex functions as variables.

然而,换个角度看问题,这也归结为你的 POJO class 写得有多好。那么,让我们重新审视一下您的 Hero class:

class Hero {
    private string backgroundVideo;

    public void init() {
         this.backgroundVide = "some value on business logic";
    }

    public string getBackgroundVideo() {
        return this.backgroundVideo;
    }

}

如果你的 Hero POJO class 是按照上面的方式实现的,getBackgroundVideo() 就可以归结为一个简单的 getter,其中 returns 是一个字符串值,没有复杂的计算。当然,与本地 HTL 变量相比,函数调用会产生开销,但这将是最小的并且可能不会引起注意。

总而言之,实际效果只能通过 POJO 实现来衡量,但 HTL 变量方法几乎总能为您带来缓存优势。