Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mustache: read variables from parent section in child section

Tags:

php

mustache

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'
                        ),
                    ),
                ));
like image 963
khairil Avatar asked Nov 01 '10 06:11

khairil


2 Answers

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.)

like image 97
sb. Avatar answered Sep 21 '22 13:09

sb.


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}}
like image 23
scc Avatar answered Sep 19 '22 13:09

scc