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.
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:
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 muchJongosi– Jongosi2013年06月21日 07:07:47 +00:00Commented 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_prepareLayoutmethod between the load and render layouts.Jongosi– Jongosi2013年06月21日 13:23:02 +00:00Commented Jun 21, 2013 at 13:23 -
Work for me very useful thx Mariusjruzafa– jruzafa2015年03月17日 15:05:16 +00:00Commented Mar 17, 2015 at 15:05