【问题标题】:Loading Underscore templates in HTML在 HTML 中加载下划线模板
【发布时间】:2014-01-29 07:54:35
【问题描述】:

我正在尝试使用脚本标签将文件中的模板加载到 HTML 文件中。我想将此用作 UnderscoreJS 中的模板 - 但我无法加载文件:

//main.js

    this.template = _.template($("#add-question").html());
            console.log("testing");
            console.log(this.template({
                question: "How are you doing?",
                yesOrNo: true
            }))

//console output:

    testing      Main.ts:37
                 Main.ts:38


    //main html file:

    <html xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html">
    <head>
        <script type="text/template" id="add-question" src="client/add-new-question.html"></script>
    </head>
    <body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
    <script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js" type="text/javascript"></script>
    <script src="https://rawgithub.com/jashkenas/underscore/master/underscore-min.js"></script>
    <script data-main="main.js" src="build/require.js"></script>

    </body>
    </html>

// 客户端/add-new-question.html

    <form id="testForm">
        <span>"<% question %></span>
        <input id="questionInput" type="text">
        <span>"<% yesOrNo %></span>
        <input id="typeInput" type="checkbox">
    </form>

更新: 这是更新后的 HTML,我在其中尝试通过正文中的脚本标记加载 html。还是不行。这就是使用 UnderscoreJS 渲染模板时的预期方式。我希望能够使用 requireJS 加载模板,但使用 underscoreJS 模板函数渲染它。

<body>
<script type="text/template" id="add-question">
    <form id="testForm">
        <span>"<%= question %></span>
        <input id="questionInput" type="text">
        <span>"<%= yesOrNo %></span>
        <input id="typeInput" type="checkbox">
    </form>
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script src="https://rawgithub.com/jashkenas/underscore/master/underscore-min.js"></script>
<script data-main="main.js" src="build/require.js"></script>
</body>

【问题讨论】:

  • 嗨,试试 而不是 。
  • @Sayuri 试过了。结果相同

标签: html underscore.js


【解决方案1】:

你必须使用&lt;%=而不是&lt;%来输出变量。

看起来你正在使用 requirejs。
因此,您还可以使用 tpl 扩展名并将下划线模板存储在 .tpl 文件中:

https://github.com/ZeeAgency/requirejs-tpl

define(['tpl!client/add-new-question.html'], function(tpl) {

        console.log(tpl({
            question: "How are you doing?",
            yesOrNo: true
        }));

});

链接:
How to use underscore.js as a template engine? underscore.js

【讨论】:

  • 我想使用 requireJs 来加载模板,但使用 Underscore 来渲染它们。我怎么做?其次,我正在使用描述的方法来加载带有下划线的寺庙,但它不起作用。请参阅问题中的更新。
  • tpl扩展已经在使用underscorejs的模板引擎
  • 我收到“未捕获的 ReferenceError:未定义定义”。我们可以用“require”代替“define”吗?
  • 在上面的语句中,我不确定如何将数据传递给模板以获取可以渲染的html。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多