Mustache: 子セクションの親セクションから変数を読み取る 質問する

Mustache: 子セクションの親セクションから変数を読み取る 質問する

Mustache では、子セクションにいるときに親セクションから変数を読み取ることは可能ですか?

例えば下の例では、{{order_store.id}}親から変数を読み込む$order_store[(現在の子ループの配列インデックス)]['id']

テンプレート.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}}

サンプルデータ(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'
                        ),
                    ),
                ));

ベストアンサー1

Mustache では親オブジェクトを参照できません。子セクション内で表示するデータはすべて、子配列に含まれている必要があります。

例えば:

$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'
        ),
    ),
));

次に、 タグ を使用できます{{order_store_id}}

この場合、ドット表記は役に立ちません。親配列に魔法のようにアクセスできるわけではありません。(ちなみに、ドット表記はすべての Mustache パーサーでサポートされているわけではないので、将来別のプログラミング言語でテンプレートを再利用する可能性がある場合は、ドット表記の使用を避けるのが最善です。)

おすすめ記事