Tutorial :smarty variables inside javascript



Question:

I am trying to use smarty variables inside javascript inside tpl

{literal}  <script language="javascript">    google.load('visualization','1',{'packages': ['geomap']});    google.setOnLoadCallback(drawMap);        function drawMap() {      var data = new google.visualization.DataTable();      data.addRows(4);      data.addColumn('string', 'Location');      data.addColumn('number', 'Number of links');    {/literal}{foreach from=$last5 item=link name=links key=index}      data.setValue({$index},0,'{$link.location|replace:'\'':'\\\''}');      data.setValue({$index},1,{$link.location_count});  {/foreach}{literal}        var options = {};      options['dataMode'] = 'regions';      options['region'] = 'world';        var container = document.getElementById('map');      var geomap = new google.visualization.GeoMap(container);        geomap.draw(data, options);    };  </script>  {/literal}  

can you suggest me a solution please


Solution:1

Simply close the {literal} tag right before inserting the smarty variable, and re-open it again.

Or use {ldelim} and {rdelim} for the pieces of code where you assign values from Smarty.


Solution:2

{literal}  function doSomething(myNumber){    var result = myNumber/{/literal}{$myDivider}{literal};    // rest of code...  }  // more functions...  {/literal}  

or

{literal}  function doSomething(myNumber){  {/literal}     var result= myNumber/{$myDivider};  {literal}    // rest of code...  }  // more functions...  {/literal}  

or

function doSomething(myNumber){ldelim}     var result= myNumber/{$myDivider};     // rest of code below...  {rdelim}    function doSomeMore(another){ldelim}     alert('{$myHello}');     // more code  {rdelim}  

OR (with Smarty 3.x and above, no literals etc necessary)

function doSomething(myNumber){     var result = myNumber/{$myDivider};     // rest of code   }  

In Smarty 3 a left curly brace with a space character (space, tab or newline) next to it should not mess with the Smarty logic any more. Problems solved by using the new version :)


Solution:3

After trying (karvonen) answers [I did not try {rdelim} though, only tried {literal}], I got a problem with my ajax requests, it stopped fetching any date from server on loading after the smarty breaking in JS. So, what I did is I assigned the smarty value to a hidden field (I know this is not most smart thing to do) and then requested that value from JS and hence assigned it to a variable. Hope this helps.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »