In response to a retweet of adam_webdev by kalenjordan
Magento’s flexible layout system makes adding a javascript library like handlebars a cinch.
First, download the latest version of handlebars and drop it in your root javascript folder
js/handlebars-v1.3.0.js
Next, add the following to your local.xml
file.
<layout>
<!-- this adds the javascript to the page. This needs to be in a layout update xml -->
<default>
<reference name="head">
<action method="addJs"><script>handlebars-v1.3.0.js</script></action>
</reference>
</default>
<!-- this adds a handlebars template to the page. It does not need to be
in layout update XML file, we're putting it there for convience -->
<cms_index_index>
<reference name="content">
<block type="core/text" name="example_handlebars_template">
<action method="setText"><text><![CDATA[
<script id="entry-template" type="text/x-handlebars-template">
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>
</script>
]]></text></action>
</block>
</reference>
</cms_index_index>
<!-- this adds a prototype js dom:ready listener to replace the body content
with our template. This does not need tobe in a layout update XML file
we're putting it here for convenience -->
<cms_index_index>
<reference name="content">
<block type="core/text" name="example_handlebars_usage">
<action method="setText"><text><![CDATA[
<script type="text/javascript">
document.observe("dom:loaded", function() {
var source = $('entry-template').innerHTML
var template = Handlebars.compile(source);
var context = {title: "My New Post", body: "This is my first post!"};
var html = template(context);
$($$('.col-main')[0]).update(html);
});
</script>
]]></text></action>
</block>
</reference>
</cms_index_index>
</layout>
Only the first <default/>
is actually required to be in a layout update XML file. The two <cms_index_index/>
handles are used to
- Add a handlebars template to the page
- Add a simple init script to the
dom:ready
event, showing how you might use the library with Prototype JS.
Also, the <default/>
node doesn’t need to be in local.xml
— you could create you own Magento module, use it to add a custom layout update XML file, and add the addJs
call there.
Assuming you theme’s CMS index page has a div with the class .col-main
, the above code sample will replace the main content of the homepage with a rendered handlebars template.
If you’re unfamiliar with the Magento layout terms above, you may be interested in my Magento for PHP MVC developers series of blog posts, or my book No Frills Magento Layout.