【问题标题】:jquery and HTML5's template tagjquery 和 HTML5 的模板标签
【发布时间】:2015-01-26 08:34:13
【问题描述】:

我想使用 underscorejs 的模板功能。似乎 HTML5 的 <template> 标记非常适合这个,但是有一个障碍...... underscorejs 插值标记(<%%> 被 html 转义,所以模板标记中的 HTML 看起来像这样:

$('template.new-email').html()

=>

"
  <div class="email">
    <div class="timestamp">
      &lt;%= received %&gt;
    </div>
    <div class="from">
      &lt;%= from %&gt;
    </div>
    <div class="title">
      &lt;%= title %&gt;
    </div>
    <div class="message">
      &lt;%= message %&gt;
    </div>
  </div>
"

嗯,那糟透了

现在,事实证明,如果我使用具有虚构类型的脚本标签,例如“x-underscore-templates”,那么它看起来很漂亮:

$('.new-email').html()

=>

"
  <div class="email">
    <div class="timestamp">
      <%= received %>
    </div>
    <div class="from">
      <%= from %>
    </div>
    <div class="title">
      <%= title %>
    </div>
    <div class="message">
      <%= message %>
    </div>
  </div>
"

所以我的问题是——我可以使用模板标签吗?如何在字符串中获取我需要的字符,以便将它们传递给下划线的模板系统?

注意 - 由于我现在使用的服务器是 hapijs / node 服务器,它使用把手作为服务器端模板系统,我不能只使用 {{ 和 }}。

【问题讨论】:

    标签: jquery html templates underscore.js-templating html5-template


    【解决方案1】:

    我也喜欢使用模板标签的想法,并且我尝试让下划线模板以各种方式在 html5 模板元素中工作。不幸的是,template element 专门表示 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>
    

    然后他们被隔离以安全地执行以下操作:

    var templates = $('.underscore-templates').prop('content');
    _.template($(templates).children('#new-email').html(), {...});
    

    使用模板元素作为范围来防止 id 冲突的正常问题并将这些模板作为脚本执行。

    (不过,这将仅限于现代浏览器,而无需深入研究如何(或者是否)可以在旧浏览器中检索模板元素内容并将其呈现为可搜索的片段。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-14
      • 2016-09-02
      • 1970-01-01
      • 2011-04-30
      • 2017-02-16
      • 2023-04-05
      • 2013-07-30
      • 1970-01-01
      相关资源
      最近更新 更多