User Tools

Site Tools


Sidebar

tutorials:using_javascript_in_smarty_templates:start

This is an old revision of the document!


Using JavaScript inside SMARTY Templates

On occasion, it may be appropriate to add a block of JavaScript code to one of your template files. One of the most common uses of this is when adding Google Analytics to a site. There is one important caveat to be aware of: both JavaScript and SMARTY have different interpretations of the left-curly-brace character '{' – if you try to insert JavaScript code containing {curly braces} into a SMARTY template file, SMARTY will attempt to interpret the braces as its own tags, which will usually break the JavaScript code.

There are a couple of ways around this. You can either replace all of the left-curly-braces in your Javascript with the {ldelim} tag, or you can simply wrap the entire javascript code in {literal}{/literal} SMARTY tags.

We'll show the oft-offending piece of Google Analytics code here, by way of example. Google generally supplies the code like this:

<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("your_tracker_number_here");
pageTracker._trackPageview();
} catch(err) {} }</script>

To properly use that code snippet in a SMARTY template, you'll want to do something like this:

{literal}
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("your_tracker_number_here");
pageTracker._trackPageview();
} catch(err) {} }</script>
{/literal}

Alternatively, the following will work just as well:

<script type="text/javascript">
try {ldelim}
var pageTracker = _gat._getTracker("your_tracker_number_here");
pageTracker._trackPageview();
} catch(err) {ldelim} } }</script>
tutorials/using_javascript_in_smarty_templates/start.1272657086.txt.gz · Last modified: 2014/09/25 16:55 (external edit)