Prestashop,在 .tpl 中,如何在 <script 内容中使用 smarty 变量?

Prestashop, in .tpl, how to use smarty variable in <script content?

我希望在我的 javascript 中使用 smarty 变量,但我并非无法做到这一点 ><'

我当前的代码但是产生错误=>

<script type="text/javascript">
var title = document.title;
var height1 = {$mysmartyvariable1};
var height2 = {$mysmartyvariable2};
if (title == 'index')
{ var height = height1; }
else { var height = height2; };

$(document).on("scroll",function(){
    if($(document).scrollTop()>height){
        $("#nav").removeClass("navfull").addClass("navsmall");
    } else{
        $("#nav").removeClass("navsmall").addClass("navfull");
    }
});
</script>

那么如何在这个脚本部分添加 mysmartyvariable1 呢?

#

感谢 Allan Nienhuis 正确的代码是:

<script type="text/javascript">
var title = document.title;
var height1 = {$mysmartyvariable1};
var height2 = {$mysmartyvariable2};
{literal}
if (title == 'index')
{ var height = height1; }
else { var height = height2; };

$(document).on("scroll",function(){
    if($(document).scrollTop()>height){
        $("#nav").removeClass("navfull").addClass("navsmall");
    } else{
        $("#nav").removeClass("navsmall").addClass("navfull");
    }
});
{/literal}
</script>

我发现您的代码存在两个问题。

1) 你没有在 $mysmartyvariable2 两边加上 {} 括号。这会将 'undefined' 分配给 height2,因为 smarty 根本不会处理这个变量,并且未定义名为 $mysmartyvariable2 的 javascript 变量。

2) 在嵌入使用 { } 字符的 javascript 时,您需要随时使用 {literal} {/literal} 标签,这样 smarty 就不会尝试解释 javascript {}字符作为聪明的语法。

http://www.smarty.net/docsv2/en/language.function.literal

在这种情况下,您可以在 height2 之后开始 {literal} 标签 declaration/assignment,因为前面的行应该由 smarty 解释,但后面的行不应该由 smarty 解释。

var height2 = {$mysmartyvariable2};
{literal}
if (title == 'index') 
  { //code here 
  }

// other code
{/literal}
</script>