如何在Magento中将CSS文件添加到CUSTOM WIDGET?

时间:2013-02-15 09:13:20

标签: javascript css magento widget

所以,我有 Magento 自定义小部件(就像产品的幻灯片一样)。

并希望在我的小部件中添加自定义 CSS / Javascript

我不希望每次都显示(加载)CSS / JS文件。


我想在PAGE包含自定义小工具时加载JS / CSS。

感谢。

2 个答案:

答案 0 :(得分:3)

这取决于您是否已将窗口小部件添加为窗口小部件实例(CMS - >窗口小部件),或者已将其包含在页面,静态块或电子邮件的内容区域中,如下所示:{{widget type="blabla/carousel"}}

如果您已将其作为窗口小部件实例包含,则可以添加如下资源:

protected function _prepareLayout() {
    if ($head = $this->getLayout()->getBlock('head')) { 
        $head->addCss('myfile.css');
    }
    return parent::_prepareLayout();
}

..在您的块中实现Mage_Widget_Block_Interface

(见http://www.magentocommerce.com/boards/viewthread/212110/

AFAIK,当您将窗口小部件作为模板指令包含在内时,无法添加资源。这只是因为HTML头已经输出了它的HTML:模块指令(例如{{widget}}{{var}})在块的_toHtml阶段被注意到。在已经渲染的块上调用任何方法都不会产生任何影响。

另请参阅$processor->filter

_toHtml方法中的Mage_Cms_Block_Page来电
protected function _toHtml()
{
    /* @var $helper Mage_Cms_Helper_Data */
    $helper = Mage::helper('cms');
    $processor = $helper->getPageTemplateProcessor();
    $html = $processor->filter($this->getPage()->getContent());
    $html = $this->getMessagesBlock()->toHtml() . $html;
    return $html;
}

答案 1 :(得分:1)

我知道这个问题相当陈旧,但是如果有人在寻找添加CSS或javascript的方法,只有当包含magento小部件时(不要求它像答案中那样是“小部件实例”)由Erfan提供)我建议在你的phtml模板文件中使用一个小的ajax脚本。如果您的设计包不使用jQuery,那么您的代码可能会有所不同。

jQuery(document).ready(function(){
jQuery.when(
    jQuery.ajax({
        type: "GET",
        url: "<?php echo $this->getSkinUrl('css/myWidget.css');?>",
        success: function(data){
            jQuery("head").append("<style>" + data + "</style>");
        },
        dataType: "html",
        cache: false,
    }),
    jQuery.ajax({
        type: "GET",
        url: "<?php echo $this->getSkinUrl('js/myWidget.js');?>",
        dataType: "script",
        cache: false,
    })

).then(function(){
        myWidget.setupFunction();
    });   
});