如何在Magento中以编程方式添加JS?

问题描述:

我需要在块文件中有条件地和以编程方式添加JS文件.我尝试了以下代码:

I need to add a JS file conditionally and programmatically inside a block file. I tried with these codes:

if (Mage::getStoreConfig('mymodule/settings/enable')) {
$this->getLayout()->getBlock('head')->addJs('path-to-file/file1.js');
} else {
$this->getLayout()->getBlock('head')->addJs('path-to-file/file2.js');
}

但是,无论设置如何,都不会加载该文件.我什至试图消除这种情况,只显式地加载一个文件,但仍然无法正常工作.我在这里做错了什么?

However, regardless of what the setting is, none of this file is loaded. I even tried to eliminate the condition and explicitly load one file only, but it still doesn't work. What have I done wrong here?

此处的问题可能是处理顺序之一.我的猜测是在渲染head块之后正在评估您的PHP代码.当您的代码成功更新head block类实例时,它是在从该实例生成输出之后发生的.

The issue here is likely one of processing order. My guess is that your PHP code is being evaluated after the head block has been rendered. While your code is successfully updating the head block class instance, it's happening after output has been generated from that instance.

更好的解决方案是在布局XML中添加addJs()调用,以便在渲染之前对其进行处理.如果有一个ifnotconfig属性会很好,但是现在您可以使用一个帮助器.

The better solution will be to add the addJs() calls in layout XML so that they will be processed prior to rendering. It would be nice if there were an ifnotconfig attribute, but for now you can use a helper.

使用一种方法创建助手类,该方法根据配置设置返回脚本路径,然后将其用作返回参数.

Create a helper class with a method which returns the script path based on the config settings, then use this as the return argument.

<?php 
class My_Module_Helper_Class extends Mage_Core_Helper_Abstract
{
    public function getJsBasedOnConfig()
    {
        if (Mage::getStoreConfigFlag('mymodule/settings/enable')) {
            return 'path-to-file/file1.js';
        }
        else {
            return 'path-to-file/file2.js';
        }
    }
}

然后使用布局XML:

<?xml version="1.0"?>
<layout>
    <default>
        <reference name="head">
            <action method="addJs">
                <file helper="classgroup/class/getJsBasedOnConfig" />
                <!-- i.e. Mage::helper('module/helper')->getJsBasedOnConfig() -->
            </action>
        </reference>
    </default>
</layout>