3

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

<layout>
    ...
    <reference name="head">
        <action method="addJs">
            <script>namespace_module/script.min.js</script>
        </action>
    </reference>
    ...
</layout>

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

Mage::app()->getLayout()->getBlock('head')->addJs('namespace_module/script.min.js');

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.

5

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:

Mage::app()->getLayout()->getBlock('head')->addJs('js/path/here.js');

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 '13 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 '13 at 13:23
  • Work for me very useful thx Marius – jruzafa Mar 17 '15 at 15:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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