【问题标题】:How can I perform maths in a silverstripe template?如何在 silverstripe 模板中进行数学运算?
【发布时间】: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


【解决方案1】:

下面的代码应该可以工作。

模板:

<div class="row">
    <% loop $ProductSectionBlocks %>
        <% if $Top.ProductSectionBlocksMod != 0 && $Top.ProductSectionBlocksMod == $FromEnd %>
            <%-- Bootstrap ^4 offset --%>
            <%--<div class="col-sm-4 offset-sm-{$Top.ProductSectionBlocksOffset}">--%>

            <%--Bootstrap 3 offset--%>
        <div class="col-sm-4 col-sm-offset-{$Top.ProductSectionBlocksOffset}">
            Column #{$Pos}
        <% else %>
        <div class="col-sm-4">
            Column #{$Pos}
        <% end_if %>
    </div>
    <% end_loop %>
</div>

页面控制器:

public function getProductSectionBlocks()
{
    return Page::get()->limit(5); // Replace 'Page' with your real DataObject
}

public function ProductSectionBlocksMod()
{
    return ($this->getProductSectionBlocks()->count() % 3);
}


public function ProductSectionBlocksOffset()
{
    return 6 - ($this->ProductSectionBlocksMod() * 2);
}

【讨论】:

  • 函数必须进入模型而不是 PageController,但它工作正常。谢谢你给我所有的语法,否则我会花很多时间在这上面。
  • 没问题,很高兴能帮上忙!好的,很高兴听到您设法解决了问题:)
猜你喜欢
  • 2011-09-11
  • 2018-02-21
  • 2019-07-16
  • 2020-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多