Mustache JS Templating - How do I embed a variable in a script tag string?

孤人 提交于 2019-11-30 19:12:42

To avoid automatic escaping in Mustache use {{{token}}} instead of {{token}}.

It seems like your template is in HTML and trying to retrieve the template using html() results in a pre-URL-escaped template to be returned. Try placing your template inside a <script type="text/html"> tag instead.

When you embed your template inside an HTML element that excepts more HTML elements as children, it may get processed by the browser as HTML. Escaping may occur. By using a <script> tag with a non-script content type, you're basically telling the browser not to touch your template.

It looks like your script is getting requested before Mustache has a chance to update the src property. What you want to do is define the template in a way that it's not parsed as part of the DOM. A common approach is to define your template inside of a <textarea> tag. This will preserve formatting and prevent character escaping.

<textarea id="gist-detail-template" style="display:none">
  <script src='http://gist.github.com/{{id}}.js'></script>
</textarea>

Now, to instantiate the template:

var template = $('#gist-detail-template').val();
var html = Mustache.to_html(template, yourTemplateData);

Here's an official example: http://mustache.github.com/#demo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!