【发布时间】:2018-12-11 02:34:03
【问题描述】:
我来自 Rails 背景,正在开发一个使用 PHP 7.1 的 Silverstripe 3.7 项目,我需要对模板进行更改以解决列对齐问题。
如果我在 Rails 中进行此更改,模板中的代码可能如下所示:
<% items = ['item1', 'item2', 'item3, 'item4'] %>
<% len = items.length %>
<% mod = len % 3 %>
<% items.each_with_index do |item, index| %>
<% if mod != 0 && mod == len-index %>
<div class="col-sm-4 col-sm-offset-<%= 6 - (mod*2) %>">
<% else %>
<div class="col-sm-4">
<% end %>
<% end %>
在发现您似乎无法在模板中进行数学运算之前,我在 Silverstripe 中尝试过的是:
<% loop $ProductSectionBlocks %>
<% if $TotalItems % 3 != 0 && $TotalItems % 3 == $FromEnd %>
<div class="col-sm-4 col-sm-offset-{6 - (($TotalItems % 3) * 2)}">
<% else %>
<div class="col-sm-4">
<% end_if %>
<% end_loop %>
我读过here 说“你应该在你的对象上创建一个包含逻辑的方法并调用它。”,但我不确定如何将这个建议应用于这种情况。
我怀疑它最终会是什么样子:
function ProductSectionBlocksMod() {
return ProductSectionBlocks.length % 3;
}
function ProductSectionBlocksOffset() {
return 6 - (ProductSectionBlocksMod * 2);
}
<% loop $ProductSectionBlocks %>
<% if $ProductSectionBlocksMod != 0 && $ProductSectionBlocksMod == $FromEnd %>
<div class="col-sm-4 col-sm-offset-{$ProductSectionBlocksOffset}">
<% else %>
<div class="col-sm-4">
<% end_if %>
<% end_loop %>
谁能指出我如何以 Silverstripe 的方式做到这一点的正确方向?
【问题讨论】:
标签: silverstripe