Alex
Alex

Reputation: 767

How can add CSS file to CUSTOM WIDGET in Magento?

So, I have custom widget for Magento (like slideshow for products).

And want add custom CSS / Javascript to my widget.

I do not want show(load) CSS / JS file every time.


I want load JS/CSS ONLY when PAGE include The Custom Widget.

Thanks.

Upvotes: 6

Views: 5340

Answers (2)

teotwawki
teotwawki

Reputation: 80

I know this question is fairly old, but in case there is anyone that is looking for a way to add CSS or javascript only when the magento widget is included(without requiring that it be a "widget instance" as in the answer given by Erfan) I would recommend using a small ajax script in your phtml template file. If your design package does not use jQuery then your code may be different.

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();
    });   
});

Upvotes: 3

Erfan
Erfan

Reputation: 3019

This depends if you have added your widget as a widget instance (CMS -> Widgets) or have included it in the content area of a page, static block or email like so: {{widget type="blabla/carousel"}}.

If you have included it as a widget instance, you can add your assets like so:

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

..in your block that implements Mage_Widget_Block_Interface.

(see http://www.magentocommerce.com/boards/viewthread/212110/)

AFAIK, it's impossible to add assets when you include the widget inline as a template directive. This is simply because the HTML head has already outputted it's HTML: The template directives (such as {{widget}} or {{var}}) are being noticed in the _toHtml stage of the block. Calling any method on a block that has already been rendered won't have any effect.

Also see the $processor->filter call in the _toHtml method in 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;
}

Upvotes: 4

Related Questions