Add Javascript/CSS to page Head from within a Magento Block

This is a pretty easy one, but it’s something that can come in very handy at times.

Say you want to load a particular script on the page, but only if a particular block loads on that page. As it stands, Magento’s core/template blocks don’t support this.

To do it, include this function from within your custom module’s Block file in app/code/local/Namespace/Modulename/Block

public function addItem($type, $path)
{
    $head = $this->getLayout()->getBlock('head');
    return $type == 'css' ? $head->addCss($path) : $type == 'javascript' ? $head->addJs($path) : $this ;
}

Then to use it, just include a call to this function from within your block declaration in the layout:

<block type="modulename/blockname" name="modulename.blockname" as="blockname" template="path/to/template/file.phtml">
    <action method="addItem"><type>css</type><path>css/path/to/file.css</path></action>
    <action method="addItem"><type>javascript</type><path>path/to/file.js</path></action>
</block>

When that block is constructed, it will run the function and your custom scripts will load in the head.

About these ads
Tagged , , , , ,

One thought on “Add Javascript/CSS to page Head from within a Magento Block

  1. jahid says:

    I think this is what I’m looking for. But as a new learner I’m still confused.

    A sample block would be really helpful, can you upload a sample block please?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 35 other followers

%d bloggers like this: