简体   繁体   中英

smarty variables inside javascript

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

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.

{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 :)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM