1

我是 Magento 的初学者,我想通过布局 xml 文件在正文部分添加 javascript 文件。

<reference name='?????'>
<action method="addJs"><script>js/my_javascript_file.js</script></action>
</reference>

参考名称应该是什么?我尝试了除“head”以外的其他引用,但它会产生错误..

我用谷歌搜索了很多,但没有得到任何解决方案。是否可以通过布局 xml 文件将 javascript 文件添加到正文部分?我不想将 Javascript 文件添加到 html 头部。
这时候我将Javascript文件直接添加到.phtml文件中......

提前致谢..

4

1 回答 1

0

在 Magento xml 中,action method="method_name" 指的是引用的块代码中的方法。其他块对象可能没有定义“addJs”方法。

“method_name”指的是对应于块核心代码的代码。例如,在 app\code\core\Mage\Page\Block\Html\head.php 中:

public function addJs($name, $params = "")
{
    $this->addItem('js', $name, $params);
    return $this;
}

因此,要将外部 js 添加到任何其他块,您必须编辑底层代码(如果您尝试,将文件移动到 app\code\local...)并添加几种方法以使其正常工作。


正如他们所说,给猫剥皮的方法不止一种(不是你想要的......)。更容易做的是使用代码制作一个 .phtml 模板文件来创建外部链接。

例如,如果我要使用以下内容制作 ext_js.phtml:

<?php $_jsExtNames = array('extra1.js' , 'extra2.js'); ?>

<?php foreach($_jsExtNames as $_jsExtName): ?>
    <script src="<?php echo $this->getSkinUrl('js/'.$_jsExtName) ?>"></script>

<?php endforeach; ?>

其中 $_jsExtNames 数组是主题 skin/js 文件夹中的外部 js 脚本列表。

The matter of adding it to your XML can change depending on where you are adding it. For default areas, something like this would work if I placed my .phtml file in page/html folder:

<default>
    <reference name="footer">
        <block type="core/template" name="extra_js" template="page/html/ext_js.phtml" />
    </reference>
</default>

That works just fine on its own. If you place it within another block, you will need to call it within that block's template file.

To illustrate that example, if I wanted to place my external js within the category view page, I would add it to category.xml like so:

<catalog_category_layered translate="label">
    <label>Catalog Category (Anchor)</label>
        <reference name="left">
            <block type="catalog/layer_view" name="catalog.leftnav" after="currency" template="catalog/layer/view.phtml"/>
        </reference>
        <reference name="content">
            <block type="catalog/category_view" name="category.products" template="catalog/category/view.phtml">
                <!-- Added Line Below -->
                <block type="core/template" name="extra_js" template="page/html/ext_js.phtml" />

Now we'll have to call the block by its name by adding this line where we would like it to go in the file catalog/category/view.phtml:

<?php echo $this->getChildHtml('extra_js'); ?>

That should work, I was testing it all out on my install while I was typing.

于 2013-05-24T19:21:50.190 回答