Only load stylesheet on Widget pages

How can I dynamically load stylesheets into the “head” section in Magento only on pages that include a custom Widget?

For my scripts I’m doing this:

if($this->getLayout()->getBlock('namespace_module_scripts')==false) {
    $block = $this->getLayout()
        ->createBlock('core/template', 'namespace_module_scripts')
        ->setTemplate('namespace/module/scripts.phtml');
    $this->getLayout()->getBlock('before_body_end')->insert($block);
}

This is the current content of _prepareLayout() in my Widget block class. I tried using the same method for styles, swapping before_body_end for head, and that worked great for placing Widget Instances or manually placing the block in my layout xml, however when inserting a widget inline in a Page’s content the head section seems to be rendered prior to the Widget, and therefore my styles template can’t be inserted into the head block.

My (hopefully) temporary solution is to load the styles on every page in my layout xml. Is there a better way to do this?

One thought on “Only load stylesheet on Widget pages”

  1. It looks like you’re SOL with widgets you’re inserting into CMS pages via the

    {{widget...}}}
    

    tag. Unlike instances, or adding it directly via a Package Layout XML update file, Magento appears to render these blocks on the fly. That is, its not until toHtml is called on the CMSs content block that Magento instantiates a {{widget...}} block. By then the head block has already rendered, and manipulating it programmatically no longer has any effect.

    Here’s the approach I’d take. It sounds adding javascript still works (which makes sense, as the CMS content block will be rendering before the before_body_end block.) Look into techniques for loading CSS files via Javascript (older link, google around if you want something web 2ish). That way you can add a javascript block that can add a CSS file. This way all your code is still confined to the widget, and you still get validating html output. It’s a pretty common technique.

    Other approaches include

    1. Just added your styles to the document inline. Bad HTML practices and all that (style aren’t in the head), but you wouldn’t be the first person to do this.

    2. Having a block that’s always added to the head, and contains conditional rendering logic. Immediately prior to rendering, have it check the layout object for your widget (via the type) OR have it check if this request is for a CMS page, and if it is check CMS page’s content for a directive ({{widget...}}) for rendering your widget. If either is true, have CSS link rendered. If it isn’t, the link doesn’t render.

Leave a Reply

Your email address will not be published. Required fields are marked *