使用twig模板引擎访问数组

时间:2016-09-02 09:35:56

标签: php symfony twig

很少被某些东西困住....我能够抓住{{value.title}}显示正常然而得到它没有显示的内部数组值并且不确定我在这里做错了什么...从未使用过twig在此之前可能只是我错过了一些东西。

PHP

  $product_array = array();

  foreach ($shopifyProducts as $product) {
      $item = array(
          "title" => $product["title"], // product title
          "variants" => array() // for now an empty array, we will fill it in the next step
      );
      foreach($product["variants"] as $variant) {
          $item["variants"][] = array(
              "barcode" => $variant["barcode"], // product barcode
              "sku" => $variant["sku"] // product SKU
          );
      }
      $product_array[] = $item; // now we add the item with all the variants to the array with all the products
  }

TWIG

<div class="table-responsive">
    <table class="table">
      <thead>
        <th>Title</th>
        <th>Barcode</th>
        <th>SKU</th>
      </thead>
      <tbody>
        <tr ng-repeat="value in remote_data">
          <td>{{ value.title }}</td>
          <td>{{ value.variants.barcode }}</td>
          <td>{{ value.variants.sku }}</td>
          <td>{{ value.variants }}</td>
        </tr>
      </tbody>
   </table>
</div>

如果输出vaule.variants,则输出

[{"barcode":"5060315468600","sku":"PLU#1"}]

但似乎不能让条形码和sku显示任何想法?

1 个答案:

答案 0 :(得分:1)

variants属性是一个数组,你应该在其中循环,例如:

{% for variant in value.variants %}

<td>{{ value.title }}</td>
<td>{{ variant.barcode }}</td>
<td>{{ variant.sku }}</td>

{% endfor %} 

Here a working example with the sample data provided

可能看到你的代码,你更好地改变你的数据结构(你需要始终显示产品的标题)并简化树枝代码,例如我建议你:

<强> PHP

$product_array = array();

foreach ($shopifyProducts as $product) {

    foreach($product["variants"] as $variant) {
        $product_array[] = array(
            'title' => $product["title"], // always display the product title
            "barcode" => $variant["barcode"], // product barcode
            "sku" => $variant["sku"] // product SKU
        );
    }// end foreach
}// end foreach

<强> TWIG

<div class="table-responsive">
    <table class="table">
      <thead>
        <th>Title</th>
        <th>Barcode</th>
        <th>SKU</th>
      </thead>
      <tbody>
        <tr ng-repeat="value in remote_data">
          <td>{{ value.title }}</td>
          <td>{{ value.barcode }}</td>
          <td>{{ value.sku }}</td>
        </tr>
      </tbody>
   </table>
</div>