Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generating Dynamic Javascript for a Magento Module
<!-- app/design/frontend/default/default/layout/acme-dynamic.xml -->
<?xml version="1.0"?>
<layout version="0.1.0">
<acme_dynamic_js_index>
<reference name="root">
<action method="setTemplate"><template>acme/dynamic/js.phtml</template></action>
</reference>
</acme_dynamic_js_index>
</layout>
<!-- app/etc/modules/Acme_Dynamic.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<config>
<modules>
<Acme_Dynamic>
<codePool>local</codePool>
<active>true</active>
</Acme_Dynamic>
</modules>
</config>
<!-- app/code/local/Acme/Dynamic/etc/config.xml -->
<!--?xml version="1.0"?-->
<config>
<modules>
<Acme_Dynamic>
<version>0.1.0</version>
</Acme_Dynamic>
</modules>
<frontend>
<routers>
<dynamic>
<use>standard</use>
<args>
<module>Acme_Dynamic</module>
<frontName>dynamic</frontName>
</args>
</dynamic>
</routers>
<layout>
<updates>
<dynamic>
<file>acme-dynamic.xml</file>
</dynamic>
</updates>
</layout>
</frontend>
</config>
<?php // app/design/frontend/default/default/template/acme/dynamic/js.phtml
/*
* Use this file to generate your JS magic. For example:
*/
$_product = Mage::getModel('catalog/product')->load(27); // for the sake of the example
?>
jQuery(document).ready(function($){
$('#featured').html('Featured Product: <?php echo $_product->getName() ?>');
});
<?php // app/code/local/Acme/Dynamic/controllers/JsController.php
class Acme_Dynamic_JsController extends Mage_Core_Controller_Front_Action {
public function indexAction() {
// Set the appropriate content-type
$this->getResponse()->setHeader('Content-type', 'text/javascript');
// Loads and renders the layout file we will create soon
$this->loadLayout();
$this->renderLayout();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment