James
James

Reputation: 1706

Accessing in arrays using Twig templating engine

I am able to grab {{ value.title }} which displays fine however getting the inner array value it is not showing and not sure what I'm doing wrong here. I have not used Twig before.

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>

If I output value.variants it outputs

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

But I can't seem to get the barcode and sku to display.

Upvotes: 1

Views: 64

Answers (1)

Matteo
Matteo

Reputation: 39460

The variants attribute is an array, you should cycle in it, as example:

{% 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.

Probably, seen your code, is better you change the structure of your data (you need to display always the product's title) and simplify the twig code, as example I propose you the following:

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>

Upvotes: 1

Related Questions