簡體   English   中英

Symfony2動態顯示從數組到樹枝的值

[英]Symfony2 displaying dynamically values from array to twig

我有一個函數,可以計算每個產品的最終價格並將其保存在數組中。 現在,當我想要顯示值時,我會陷入如何動態顯示所有值的困境。

這是功能:

public function getTotal($items)
{
    $total = array();
    foreach($items as $key=>$item){
        $total[$key] = $item->getPrice() - $item->getDiscount() + $item->getValue();
    }
    return $total;
}

所有方法getValue,getDiscount等均有效。

這是我嘗試顯示的方式:

{{ getTotal(product)[key]}}

問題是當我寫例如{{ getTotal(product)[0]}}{{ getTotal(product)[1]}}等時,我得到正確的值,但只有1個產品。 我需要從所有這些中獲取價值。

如果我做{{ getTotal(product)[key]}}我收到一個奇怪的錯誤:

第89行的MpShopBundle:Frontend:product_summary.html.twig中不存在帶有鍵“ 0、1”的數組的鍵“ 12”

我不知道為什么鍵等於12? 也許我必須寫一些不同的東西?

更新謝謝您的回答,我什至沒有考慮使用細枝進行循環,但是我終於得到了一些價值。 但是,我不知道為什么,但是樹枝循環為每個產品分配了兩個值。

這應該是這樣的:

Product1 : 0(key):145(value)
Product2 : 1:415

但這是這樣的:

Product1 : 0:145 1:415
Product2 : 0:145 1:415

這是樹枝:

 {% if product is defined %}

            {% for key, item in cart %}

              {% for item in product %}


                <tr>

                  <td> <img width="60" src="{{ asset('bundles/mpFrontend/assets/products/4.jpg') }}" alt=""/></td>

                  <td>{{ item.model }}</td>
                  <td>
                    <div class="input-append"><input class="span1" style="max-width:34px" placeholder="1" id="appendedInputButtons" size="16" type="text">
                    <button class="btn" type="button"><i class="icon-minus"></i></button>
                    <button class="btn" type="button"><i class="icon-plus"></i></button>
                    <button class="btn btn-danger" type="button"><a href="{{ path('cart_remove', {'id': key}) }}"><i class="icon-remove icon-white"></i></button>
                    </div>
                  </td>

                  <td>{{ item.price }}</td>
                  <td>{{ item.discount }}</td>
                  <td>{{ item.value }}</td>

                  {% if getTotal(product) is iterable %}
                    {% for key, sum in getTotal(product) %}

                     <td>{{ key }}:{{ sum }}</td>

                  {% endfor %}
                {% endif %}

                </tr>

 {% endfor %}

使用樹枝進行循環

{% for total in getTotal(product) %}
  {{ total }}
{% endfor %}

您可以使用樹枝進行循環。

例:

{% if getTotal(product) is iterable %}
    {% for key, sum in getTotal(product) %}
        {{ key }}:{{ sum }}
    {% else %}
        empty array
    {% endfor %}
{% endif %}

您不應使用循環,而應將函數從外部移到product類的方法。

代替循環:

<td>{{ product.total }}</td>

新功能:

class Product {
...
    public function getTotal()
    {
        return $this->getPrice() - $this->getDiscount() + $this->getValue();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM