在 mustache 模板中包含 javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11314477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Including javascript within mustache template
提问by BobFlemming
I have a block of javascript for displaying adverts that I wish to include every nth time on a page.
我有一个 javascript 块,用于显示我希望在页面上每第 n 次包含的广告。
I'm using Mustache as my templating language but cannot work out how to include the js so it runs as a script rather than just being inserted as a string.
我使用 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>
I've tried triple { which I hoped would escape but sadly it didn't.
我试过三重 { 我希望它会逃脱,但遗憾的是它没有。
回答by Geert-Jan
Your json-input should reference the script to call:
您的 json-input 应引用要调用的脚本:
JSON
JSON
var json = {
id: "someid",
gaFillSlot: function(){
GA_googleFillSlot("MPU");
}
}
TEMPLATE
模板
<script id="mustache-post-advert" type="text/mustache">
<article id="post-{{id}}" class="post">
{{gaFillSlot}}
</article>
</script>
Make sure 'GA_googleFillSlot' is available to be called from the context of mustache at time of templating.
确保 'GA_googleFillSlot' 可在模板时从 mustache 的上下文中调用。
This is in line with the logic-less nature of Mustache: any logic you want should be embedded into the json you pass to Mustache to bgin with.
这符合 Mustache 的无逻辑性质:您想要的任何逻辑都应该嵌入到您传递给 Mustache 以进行 bgin 的 json 中。
Didn't test this, but this should work. HTH
没有测试这个,但这应该有效。HTH
回答by Hymanwanders
You're already inside a script tag, there's no need to add another:
您已经在脚本标签中,无需添加另一个:
<script id="mustache-post-advert" type="text/mustache">
<article id="post-{{id}}" class="post">
{{ GA_googleFillSlot("MPU") }}
</article>
</script>
edit
编辑
on second thought, this may not be enough; see here for info on calling functions from within mustache templates:
再想一想,这可能还不够;有关从 mustache 模板中调用函数的信息,请参见此处:
http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-using-the-mustache-template-library/
http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-using-the-mustache-template-library/