在我正在创建的 Silverstripe 应用程序中,我有NewsArticles
具有NewsTags
(使用 silverstripe-tagfield 创建)。我正在使用NewsTags
在每个NewsArticle
的侧边栏中创建一个"相关新闻"小部件。我在NewsArticle
控制器中创建了一个RelatedArticles
操作,一切正常。
但是,为了使用RelatedArticles
操作,我被迫调用该函数三次。这不是一个大问题,但我想尽量减少调用对数据库进行多次调用的函数的次数。
这是我的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 应该只调用数据库一次,并为接下来的 2 次调用缓存RelatedArticles
结果。
为了进一步缓存查询,我们可以使用部分缓存来缓存模板的某些部分。
<% 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 %>