I need to create a block programatically (for various reasons):

$myblock = Mage::app()->getLayout()->createBlock('namespace_module/path', 'my_block', $params);

This works fine, but the controller action is skipped over when doing this. I mean, it is, right? Therefore, my XML layout file is ignored, which contains:

file: app/design/frontend/base/default/layout/namespace_module.xml

    <reference name="head">
        <action method="addJs">

I have tried adding the JS file programmatically as follows, but I get nothing at all:


I will also need to reference the CSS file. It's late, so this could be a stupid error. Any guidance/advice welcome. Thank you.

1 Answer 1


The layout and blocks are kind of in a 'one direction' relation. I mean you can reference blocks in the layout but you cannot load layout files when creating an instance of a block. Actually you could but it's not the best idea to do so. Layouts should be called by the controllers.
When manually creating an instance of a block it has nothing to do with the layout files.
As for the second part, adding a js to the head, you have the right idea. It's done like you tried:


BUT... If the head block is already rendered then it has no effect. You have to make sure the js is added to the head after loadLayout() has been called in the controller action and before you call renderLayout() in the same action.

  • Once again Marius, thx so much
    – Jongosi
    Jun 21, 2013 at 7:07
  • This method won't work on block type Mage_Core_Block_Template. I could be doing something wrong, ofc! I'm calling it in the _prepareLayout method between the load and render layouts.
    – Jongosi
    Jun 21, 2013 at 13:23
  • Work for me very useful thx Marius
    – jruzafa
    Mar 17, 2015 at 15:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.