在胡须模板中包含 JavaScript

Including javascript within mustache template

本文关键字:包含 JavaScript 胡须模      更新时间:2023-09-26

我有一个javascript块,用于显示广告,我希望每n次在页面上包含一次。

我使用 Mustache 作为我的模板语言,但无法弄清楚如何包含 js,因此它作为脚本运行,而不仅仅是作为字符串插入。

<script id="mustache-post-advert" type="text/mustache">
<article id="post-{{id}}" class="post">
    {{{  <script type="text/javascript">GA_googleFillSlot("MPU")</script>  }}}
</article>
</script>

我尝试了三重{,我希望能逃脱,但遗憾的是它没有。

您的 json 输入应引用要调用的脚本:

杰伦

 var json = {
   id: "someid",
   gaFillSlot: function(){
     GA_googleFillSlot("MPU");
   }
 }

模板

 <script id="mustache-post-advert" type="text/mustache">
   <article id="post-{{id}}" class="post">
     {{gaFillSlot}}
   </article>
 </script>

确保在模板化时可以从胡须上下文中调用"GA_googleFillSlot"。

这符合 Mustache 的

无逻辑本质:你想要的任何逻辑都应该嵌入到你传递给 Mustache 的 json 中。

没有测试这个,但这应该有效。呵呵

您已经在脚本标记中,无需添加另一个:

<script id="mustache-post-advert" type="text/mustache">
  <article id="post-{{id}}" class="post">
    {{ GA_googleFillSlot("MPU") }}
  </article>
</script>

编辑

再三考虑,这可能还不够;有关从 Mustache 模板中调用函数的信息,请参阅此处:

http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-using-the-mustache-template-library/