有两种方法来包括在Magento 2从模板的javascript:在<script type="text/x-magento-init">
和data-mage-init
属性。不管哪一种方式,能够用于将数据传递到JSON定义范围内的脚本。例如,使用X-Magento的-的init脚本标签,在模板有:javascript
<script type="text/x-magento-init"> { "*": { "js/example": { "a": "<?php echo 'Hello from template' ?>" } } } </script>
而在JS文件,你必须:php
define([ 'jquery' ], function ($) { 'use strict'; return function (config) { console.log(config); // will output {a: "Hello from template"} alert(config.a); // would be equal to alert("Hello from template"); } });