Smarty variable inside javascript

12,285

Solution 1

Smarty 2 requires escapement of the "{" and "}" characters, you can use {ldelim} and {redlim} to escape them individually or wrap entire blocks of text with {literal}{/literal}. It's usually cleaner to use {ldelim} and {rdelim} when there is embedded smarty tags, so example:

<script type="text/javascript">
  function toAlert() {ldelim}
    alert('{$text}' );
  {redlim}
</script>

Smarty 3 conveniently ignores "{" and "}" characters surrounded by white space, so your javascript example would work as-is.

Solution 2

You should put this code intp TPL file to make this work. Only TPL files are processed as Smarty files and you can use there Smarty variables.

Your code put should work out of the box in your index.tpl file but if it weren't try:

<script type="text/javascript">
{literal}
  function toAlert() {
    alert('{/literal}{$text}{literal}' );
  }
{/literal}
</script>
Share:
12,285
jmcordoba
Author by

jmcordoba

Updated on June 04, 2022

Comments

  • jmcordoba
    jmcordoba almost 2 years

    I am really starting with Smarty and I do not understand this fact:

    if I put the next code inside my template index.tpl

    <script type="text/javascript">
      function toAlert() {
        alert('{$text}' );
      }
    </script>
    

    I can access to the function toAlert and show the content of Smarty variable {{$text}}, but if I put this code into a js file lije javascript.js and I try to access it by putting into de template the link:

    I cannot access to the function as well.

    Can anyone tell me why or help wher can I find this specific info? thank you!!