Using Google Analytics Or Other Javascript With Smarty Template Engine

ga-smarty


On a website I was working on recently I added the Google Analytics tracking code to the footer of a Smarty template, like this:

footer.tpl:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXX-XX']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>


</body>
</html>

However, since the javascript used by Google Analytics includes { and } tags, also used by the Smarty template engine, it tries to interpret this code and depending on your settings will either fail silently or or with an error such as this:

Smarty error: [in footer.tpl line 148]: syntax error: unrecognized tag 'var'

The fix is simple. Enclose your Google Analytics code, or other javascript code, with {literal} and {/literal}. The literal tag allows you to place code to be displayed, well, literally.

The final code will look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{literal}

<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXX-XX']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>

{/literal}

</body>
</html>

Your website should now run properly with the Google Analytics code in place.