Tre*_*oke 5 jquery html5 templates underscore.js-templating html5-template
我想使用underscorejs的模板功能.似乎HTML5的<template>标签对于它来说是一个令人惊讶的标签,但是有一个障碍......下划线插值标签(<%并%>获得html转义,因此模板标签内的HTML看起来像这样:
$('template.new-email').html()
Run Code Online (Sandbox Code Playgroud)
=>
"
<div class="email">
<div class="timestamp">
<%= received %>
</div>
<div class="from">
<%= from %>
</div>
<div class="title">
<%= title %>
</div>
<div class="message">
<%= message %>
</div>
</div>
"
Run Code Online (Sandbox Code Playgroud)
好吧,那很糟糕.
现在,事实证明,如果我使用虚构类型的脚本标记,例如"x-underscore-templates",那么它看起来像hunky-dory:
$('.new-email').html()
Run Code Online (Sandbox Code Playgroud)
=>
"
<div class="email">
<div class="timestamp">
<%= received %>
</div>
<div class="from">
<%= from %>
</div>
<div class="title">
<%= title %>
</div>
<div class="message">
<%= message %>
</div>
</div>
"
Run Code Online (Sandbox Code Playgroud)
所以我的问题是 - 我可以使用模板标签吗?如何在字符串中获得我需要的字符,以便将它们传递给下划线的模板系统?
注意 - 由于我现在使用的服务器是使用把手作为服务器端模板系统的hapijs/node服务器,我不能只使用{{和}}.
我也喜欢使用模板标签的想法,我试图以各种方式使下划线模板在html5模板元素中工作.不幸的是,模板元素专门意味着一个html模板,内容将被转换为一个文档片段,这个片段不适用于许多有效的下划线模板,即使它们稍后会渲染为有效的html.
因此,我可以建议的唯一用法是,您可以将脚本元素组织在模板元素中,如下所示:
<template class="underscore-templates">
<script id="new-email">
<div class="email">
<div class="timestamp">
<%= received %>
</div>
<div class="from">
<%= from %>
</div>
<div class="title">
<%= title %>
</div>
<div class="message">
<%= message %>
</div>
</div>
</script>
<script id="other">
</script>
</template>
Run Code Online (Sandbox Code Playgroud)
然后他们被隔离以安全地做以下事情:
var templates = $('.underscore-templates').prop('content');
_.template($(templates).children('#new-email').html(), {...});
Run Code Online (Sandbox Code Playgroud)
使用模板元素作为范围来防止id冲突的正常问题并将这些模板作为脚本执行.
(尽管如此,这仍然局限于现代浏览器,而没有深入研究如何(或者可能)如何(或者可能)在旧浏览器中检索模板元素内容并将其呈现为可搜索的片段.)