最小化从 SilverStripe 模板调用控制器

Minimize calls to controller from SilverStripe template

Silverstripe application I am creating I have NewsArticles which have NewsTags (created using silverstripe-tagfield)。我正在使用 NewsTags 在每个 NewsArticle 的侧边栏中创建一个 "Related News" 小部件。我在 NewsArticle 控制器中创建了一个 RelatedArticles 动作,一切正常。

然而,为了使用 RelatedArticles 动作,我不得不调用函数 3 次。这不是一个大问题,但我想尽量减少调用多次调用数据库的函数的次数。

这是我的 RelatedNewsModule.ss 模板文件的精简版:

// First call to check if there are related articles
<% if $RelatedArticles %>

    // second call to get the array
    <% loop $RelatedArticles() %>
        ...
    <% end_loop %>

    // third call to check if there are more than one so we need navigation
    <% if $RelatedArticles.Count > 1 %>
            ... navigation markup
    <% end_if %>

<% end_if %>

我想调用该函数一次,并可能使用 SilverStripe 模板中的属性来引用这两个检查和文章数组。但是我不确定该怎么做。

处理这种情况的最佳方法是什么?

如评论中所述,SilverStripe 应该只调用一次数据库并缓存 RelatedArticles 接下来 2 次调用的结果。

为了进一步缓存查询,我们可以使用 Partial Caching 来缓存部分模板。

<% cached 'RelatedArticles', $ID, $List('RelatedArticles').max('LastEdited'), $List('RelatedArticles').count() %>
    <% if $RelatedArticles %>

        // second call to get the array
        <% loop $RelatedArticles %>
            ...
        <% end_loop %>

        // third call to check if there are more than one so we need navigation
        <% if $RelatedArticles.Count > 1 %>
            ... navigation markup
        <% end_if %>

    <% end_if %>
<% end_cached %>