Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve Magento store's base url in javascript

Tags:

magento

What is the best way to determine a Magento store's base url from inside javascript?

I'm working on a reusable extension that needs to know the store's base url in javascript in order to do some Ajax calls. One would think a property like

Mage.baseUrl 

would be available, but I can't find it.

An alternative would be to add the base url as a bit of inline javascript, but I can't find any information on how to add inline javascript programmatically (only external js files), without altering the template.

like image 589
Nick Daugherty Avatar asked Jan 20 '12 03:01

Nick Daugherty


1 Answers

By default this information isn't (reliably, stably) exposed via Javascript. You're going to need to expose it yourself via a custom block added to the layout. The easiest way to do this will be

  1. Adding the block via your theme's local.xml file

  2. Adding a template to your theme for the above block

To add the block to the layout via your local.xml file, something like this should suffice

<default>
    <reference name="root">
        <block name="my_custom_js_block">
            <action method="setTemplate">
                <template>my_custom_js_block/extra-js.phtml</template>
            </action>
        </block>
    </reference>
</default>

Then add the following folder and file to your theme

app/design/frontend/default/your_theme/template/my_custom_js_block/
app/design/frontend/default/your_theme/template/my_custom_js_block/extra-js.phtml

At this point you have a phtml template file that will be rendered on every page. You can add whatever javascript variables you want. I'm fond of a pattern something like

#File: app/design/frontend/default/your_theme/template/my_custom_js_block/extra-js.phtml
<?php
    $h = Mage::helper('core');
    $info = new stdClass();
    $info->base_dir = Mage::getBaseDir();
?>
<script type="text/javascript">
    var my_custom_js_block_info = <?php echo $h->jsonEncode($info); ?>;
</script>

(untested, top-of-my-head code, but should work)

like image 162
Alan Storm Avatar answered Sep 26 '22 15:09

Alan Storm