在服务器上使用 Handlebars 时的客户端模板
如果您在客户端和服务器上使用 Handlebars,您将遇到此问题,即客户端模板将由服务器上的视图引擎解析。例如,您可能有这样的文件:
<h1>My Page Title</h1>
<!-- This template should be transformed into HTML by the server -->
<div id="photoList" class="pure-g">
{{#each photos}}
<div class="photo pure-u-1-12" data-photo-id="{{id}}">
<img class="pure-u-1" src="{{src}}">
</div>
{{/each}}
</div>
<!-- This template should not be touched. It's for the client -->
<script type="text/x-handlebars" id="lightbox-template">
<img class="lightbox-image" src="{{large}}">
<div class="lightbox-meta">
<a class="pure-button lightbox-link" href="{{url}}">View on Flickr</a>
<button class="pure-button lightbox-link lightbox-hide">Hide</button>
</div>
</script>
当您在浏览器上查看时,其中的标签({{..}})将被解析出来。你会得到这样的东西,这是无用的:
<!-- I can't use this template on the client anymore!! -->
<script type="text/x-handlebars" id="lightbox-template">
<img class="lightbox-image" src="">
<div class="lightbox-meta">
<a class="pure-button lightbox-link" href="">View on Flickr</a>
<button class="pure-button lightbox-link lightbox-hide">Hide</button>
</div>
</script>
幸运的是,对此的修复非常简单,尽管没有在任何地方记录。只需在所有开始标签 ({{) 前添加一个 \。\ 将在编译步骤中被解析出来,您将在客户端拥有一个完全可用的模板。
<!-- Add a \ before the handlebars -->
<script type="text/x-handlebars" id="lightbox-template">
<img class="lightbox-image" src="\{{large}}">
<div class="lightbox-meta">
<a class="pure-button lightbox-link" href="\{{url}}">View on Flickr</a>
<button class="pure-button lightbox-link lightbox-hide">Hide</button>
</div>
</script>
来源: 链接