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.

dotancohen
1,1306 silver badges21 bronze badges
asked Jun 20, 2013 at 22:38

1 Answer 1

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.

answered Jun 21, 2013 at 7:06
3
  • Once again Marius, thx so much Commented 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. Commented Jun 21, 2013 at 13:23
  • Work for me very useful thx Marius Commented Mar 17, 2015 at 15:05

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.