Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 267
Alex Avatar asked Feb 15 '13 09:02

Alex


1 Answers

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;
}
like image 96
Erfan Avatar answered Oct 07 '22 00:10

Erfan