Is it possible in Mustache to read variable from parent section while in child section?
for instance my example below, I want the {{order_store.id}} to read variable from it's parent $order_store[(array index of current child loop)]['id']
the template.mustache
{{#order_store}}<table>
<caption>
Store Name: {{name}}
Product Ordered: {{products}}
Product Weights: {{products_weight}}
</caption>
<tbody>
{{#shipping_method}}<tr>
<td>
<input type="radio" name="shipping[{{order_store.id}}]" id="shipping-{{id}}" value="{{id}}" />
<label for="shipping-{{id}}">{{name}}</label>
</td>
<td>{{description}}</td>
<td>{{price}}</td>
</tr>{{/shipping_method}}
</tbody>
</table>{{/order_store}}
sample data (in PHP);
$order_store => array(
array(
'id' => 1,
'name' => 'Kyriena Cookies',
'shipping_method' => array(
array(
'id' => 1,
'name' => 'Poslaju',
'description' => 'Poslaju courier'
),
array(
'id' => 2,
'name' => 'SkyNET',
'description' => 'Skynet courier'
),
),
));
Mustache doesn't allow you to refer to parent objects. Any data you want to display while within the child section needs to be contained in the child array.
For example:
$order_store => array(
array(
'id' => 1,
'name' => 'Kyriena Cookies',
'shipping_method' => array(
array(
'id' => 1,
'name' => 'Poslaju',
'description' => 'Poslaju courier',
'order_store_id' => '1'
),
array(
'id' => 2,
'name' => 'SkyNET',
'description' => 'Skynet courier',
'order_store_id' => '1'
),
),
));
Then you can use the tag {{order_store_id}}
.
Dot notation wouldn't help in this case -- it won't magically give you access to the parent array. (By the way, dot notation isn't supported by all mustache parsers, so it's probably best to avoid using it if there's any chance you'll want to reuse your templates with another programming language in the future.)
If the template is to be compiled on the client side, another option is to use HandlebarsJS templates, which are compatible with Mustache, and use the parent notation:
{{../order_store.id}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With