如何使用underscore.js作为模板引擎?

发布于 2024-10-13 17:43:09 字数 325 浏览 7 评论 0原文

我正在尝试了解 javascript 作为服务器端语言和函数式语言的新用法。前几天我听说了node.js和express框架。然后我看到 underscore.js 作为一组实用函数。我在 stackoverflow 上看到了 这个问题 。它说我们可以使用 underscore.js 作为模板引擎。任何人都知道关于如何使用 underscore.js 进行模板化的好教程,特别是对于那些对高级 javascript 经验较少的大佬来说。谢谢

I'm trying to learn about new usages of javascript as a serverside language and as a functional language. Few days ago I heard about node.js and express framework. Then I saw about underscore.js as a set of utility functions. I saw this question on stackoverflow
. It says we can use underscore.js as a template engine. anybody know good tutorials about how to use underscore.js for templating, especially for biginners who have less experience with advanced javascript. Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

只想待在家 2024-10-20 17:43:09

您需要了解的有关下划线模板的所有信息都位于此处。只需记住 3 件事:

  1. <% %> - 执行某些代码
  2. <%= %> - 在模板中打印某些值
  3. <%- %> - 打印一些 HTML 转义的值

这就是全部。

简单的例子:

var tpl = _.template("<h1>Some text: <%= foo %></h1>");

然后 tpl({foo: "blahblah"}) 将被渲染为字符串

Some text: blahblah

Everything you need to know about underscore template is here. Only 3 things to keep in mind:

  1. <% %> - to execute some code
  2. <%= %> - to print some value in template
  3. <%- %> - to print some values HTML escaped

That's all about it.

Simple example:

var tpl = _.template("<h1>Some text: <%= foo %></h1>");

then tpl({foo: "blahblah"}) would be rendered to the string <h1>Some text: blahblah</h1>

月朦胧 2024-10-20 17:43:09
<!-- Install jQuery and underscore -->

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="http://documentcloud.github.com/underscore/underscore-min.js"></script>

<!-- Create your template -->
<script type="foo/bar" id='usageList'>
<table cellspacing='0' cellpadding='0' border='1' >
    <thead>
      <tr>
        <th>Id</th>
        <th>Name</th>
      </tr>
    </thead>
    <tbody>
      <%
        // repeat items 
        _.each(items,function(item,key,list){
          // create variables
          var f = item.name.split("").shift().toLowerCase();
      %>
        <tr>
          <!-- use variables -->
          <td><%= key %></td>
          <td class="<%= f %>">
            <!-- use %- to inject un-sanitized user input (see 'Demo of XSS hack') -->
            <h3><%- item.name %></h3>
            <p><%- item.interests %></p>
          </td>
        </tr>
      <%
        });
      %>
    </tbody>
  </table>
</script>

<!-- Create your target -->

<div id="target"></div>

<!-- Write some code to fetch the data and apply template -->

<script type="text/javascript">
  var items = [
    {name:"Alexander", interests:"creating large empires"},
    {name:"Edward", interests:"ha.ckers.org <\nBGSOUND SRC=\"javascript:alert('XSS');\">"},
    {name:"..."},
    {name:"Yolando", interests:"working out"},
    {name:"Zachary", interests:"picking flowers for Angela"}
  ];
  var template = $("#usageList").html();
  $("#target").html(_.template(template,{items:items}));
</script>
  • JsFiddle 谢谢@PHearst!
  • JsFiddle(最新)
  • JsFiddle列表按首字母分组(带有图像、函数调用、子模板的复杂示例)fork it!玩得开心...
  • JsFiddle @tarun_telang 下面的 XSS 黑客演示
  • JsFiddle 一种做子模板的非标准方法
<!-- Install jQuery and underscore -->

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="http://documentcloud.github.com/underscore/underscore-min.js"></script>

<!-- Create your template -->
<script type="foo/bar" id='usageList'>
<table cellspacing='0' cellpadding='0' border='1' >
    <thead>
      <tr>
        <th>Id</th>
        <th>Name</th>
      </tr>
    </thead>
    <tbody>
      <%
        // repeat items 
        _.each(items,function(item,key,list){
          // create variables
          var f = item.name.split("").shift().toLowerCase();
      %>
        <tr>
          <!-- use variables -->
          <td><%= key %></td>
          <td class="<%= f %>">
            <!-- use %- to inject un-sanitized user input (see 'Demo of XSS hack') -->
            <h3><%- item.name %></h3>
            <p><%- item.interests %></p>
          </td>
        </tr>
      <%
        });
      %>
    </tbody>
  </table>
</script>

<!-- Create your target -->

<div id="target"></div>

<!-- Write some code to fetch the data and apply template -->

<script type="text/javascript">
  var items = [
    {name:"Alexander", interests:"creating large empires"},
    {name:"Edward", interests:"ha.ckers.org <\nBGSOUND SRC=\"javascript:alert('XSS');\">"},
    {name:"..."},
    {name:"Yolando", interests:"working out"},
    {name:"Zachary", interests:"picking flowers for Angela"}
  ];
  var template = $("#usageList").html();
  $("#target").html(_.template(template,{items:items}));
</script>
  • JsFiddle Thanks @PHearst!
  • JsFiddle (latest)
  • JsFiddle List grouped by first letter (complex example w/ images, function calls, sub-templates) fork it! have a blast...
  • JsFiddle Demo of XSS hack noted by @tarun_telang below
  • JsFiddle One non-standard method to do sub-templates
泼猴你往哪里跑 2024-10-20 17:43:09

在最简单的形式中,您可以这样使用它:

var html = _.template('<li><%= name %></li>', { name: 'John Smith' });
//html is now '<li>John Smith</li>'   

如果您要多次使用模板,您将需要对其进行编译,以便速度更快:

var template = _.template('<li><%= name %></li>');

var html = [];
for (var key in names) {
    html += template({ name: names[i] });
}

console.log(html.join('')); //Outputs a string of <li> items

我个人更喜欢 Mustache 样式语法。您可以调整模板标记标记以使用双花括号:

_.templateSettings.interpolate = /\{\{(.+?)\}\}/g;

var template = _.template('<li>{{ name }}</li>');

In it's simplest form you would use it like:

var html = _.template('<li><%= name %></li>', { name: 'John Smith' });
//html is now '<li>John Smith</li>'   

If you're going to be using a template a few times you'll want to compile it so it's faster:

var template = _.template('<li><%= name %></li>');

var html = [];
for (var key in names) {
    html += template({ name: names[i] });
}

console.log(html.join('')); //Outputs a string of <li> items

I personally prefer the Mustache style syntax. You can adjust the template token markers to use double curly braces:

_.templateSettings.interpolate = /\{\{(.+?)\}\}/g;

var template = _.template('<li>{{ name }}</li>');
神魇的王 2024-10-20 17:43:09

模板的文档是部分的,我看了源代码。

_.template 函数有 3 个参数:

  1. String text:模板字符串
  2. Object data:评估数据
  3. Object settings > :本地设置,_.templateSettings 是全局设置对象。

如果没有给出数据(或 null),则将使用 render 函数回来了。它有 1 个参数:

  1. Object data :与上面的 data 相同

设置中有 3 个正则表达式模式和 1 个静态参数:

  1. RegExp evaluate : “<%代码%>”在模板字符串
  2. RegExp interpolate 中:“<%=code%>”在模板字符串
  3. RegExp escape 中:“<%-code%>”
  4. String variable :可选,模板字符串中data参数的名称

evaluate 部分中的代码将被简单评估。您可以使用 __p+="mystring" 命令将此部分中的字符串添加到评估的模板中,但不建议这样做(不是模板界面的一部分),请使用插值部分来代替。这种类型的部分用于向模板添加 if 或 for 等块。

插值部分中的代码结果将添加到评估的模板中。如果返回 null,则将添加空字符串。

escape 部分在给定代码的返回值上使用 _.escape 转义 html。因此它与 interpolate 部分中的 _.escape(code) 类似,但它使用 \ 空白字符进行转义,例如 \ n 在将代码传递给 _.escape 之前。我不知道为什么这么重要,它在代码中,但它与 interpolate_.escape 配合得很好 - 它不会逃脱空白人物——也是。

默认情况下,data 参数由 with(data){...} 语句传递,但这种评估比使用命名变量的评估慢得多。因此,使用 variable 参数命名 data 是件好事...

例如:

var html = _.template(
    "<pre>The \"<% __p+=_.escape(o.text) %>\" is the same<br />" +
        "as the  \"<%= _.escape(o.text) %>\" and the same<br />" +
        "as the \"<%- o.text %>\"</pre>",
    {
        text: "<b>some text</b> and \n it's a line break"
    },
    {
        variable: "o"
    }
);

$("body").html(html);

results

The "<b>some text</b> and 
 it's a line break" is the same
as the "<b>some text</b> and 
 it's a line break" and the same
as the "<b>some text</b> and 
 it's a line break"

您可以在此处找到更多如何使用模板并覆盖默认设置的示例:
http://underscorejs.org/#template

通过模板加载,你有很多选择,但最后你总是必须将模板转换为字符串。您可以像上面的示例一样将其作为普通字符串提供,也可以从脚本标记加载它,并使用 。 jquery 的 html() 函数,或者您可以使用 tpl 插件< require.js 的 /a>。

使用 laconic 而不是模板构建 dom 树的另一种选择。

The documentation for templating is partial, I watched the source.

The _.template function has 3 arguments:

  1. String text : the template string
  2. Object data : the evaluation data
  3. Object settings : local settings, the _.templateSettings is the global settings object

If no data (or null) given, than a render function will be returned. It has 1 argument:

  1. Object data : same as the data above

There are 3 regex patterns and 1 static parameter in the settings:

  1. RegExp evaluate : "<%code%>" in template string
  2. RegExp interpolate : "<%=code%>" in template string
  3. RegExp escape : "<%-code%>"
  4. String variable : optional, the name of the data parameter in the template string

The code in an evaluate section will be simply evaluated. You can add string from this section with the __p+="mystring" command to the evaluated template, but this is not recommended (not part of the templating interface), use the interpolate section instead of that. This type of section is for adding blocks like if or for to the template.

The result of the code in the interpolate section will added to the evaluated template. If null given back, then empty string will added.

The escape section escapes html with _.escape on the return value of the given code. So its similar than an _.escape(code) in an interpolate section, but it escapes with \ the whitespace characters like \n before it passes the code to the _.escape. I don't know why is that important, it's in the code, but it works well with the interpolate and _.escape - which doesn't escape the white-space characters - too.

By default the data parameter is passed by a with(data){...} statement, but this kind of evaluating is much slower than the evaluating with named variable. So naming the data with the variable parameter is something good...

For example:

var html = _.template(
    "<pre>The \"<% __p+=_.escape(o.text) %>\" is the same<br />" +
        "as the  \"<%= _.escape(o.text) %>\" and the same<br />" +
        "as the \"<%- o.text %>\"</pre>",
    {
        text: "<b>some text</b> and \n it's a line break"
    },
    {
        variable: "o"
    }
);

$("body").html(html);

results

The "<b>some text</b> and 
 it's a line break" is the same
as the "<b>some text</b> and 
 it's a line break" and the same
as the "<b>some text</b> and 
 it's a line break"

You can find here more examples how to use the template and override the default settings:
http://underscorejs.org/#template

By template loading you have many options, but at the end you always have to convert the template into string. You can give it as normal string like the example above, or you can load it from a script tag, and use the .html() function of jquery, or you can load it from a separate file with the tpl plugin of require.js.

Another option to build the dom tree with laconic instead of templating.

滴情不沾 2024-10-20 17:43:09

我给出一个非常简单的例子

1)

var data = {site:"mysite",name:"john",age:25};
var template = "Welcome you are at <%=site %>.This has been created by <%=name %> whose age is <%=age%>";
var parsedTemplate = _.template(template,data);
console.log(parsedTemplate); 

结果是

Welcome you are at mysite.This has been created by john whose age is 25.

2) 这是一个模板

   <script type="text/template" id="template_1">
       <% _.each(items,function(item,key,arr) { %>
          <li>
             <span><%= key %></span>
             <span><%= item.name %></span>
             <span><%= item.type %></span>
           </li>
       <% }); %>
   </script>

这是 html

<div>
  <ul id="list_2"></ul>
</div>

这是包含 json 对象并将模板放入 html 的 javascript 代码

   var items = [
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       } 
   ];
  $(document).ready(function(){
      var template = $("#template_1").html();
      $("#list_2").html(_.template(template,{items:items}));
  });

I am giving a very simple example

1)

var data = {site:"mysite",name:"john",age:25};
var template = "Welcome you are at <%=site %>.This has been created by <%=name %> whose age is <%=age%>";
var parsedTemplate = _.template(template,data);
console.log(parsedTemplate); 

The result would be

Welcome you are at mysite.This has been created by john whose age is 25.

2) This is a template

   <script type="text/template" id="template_1">
       <% _.each(items,function(item,key,arr) { %>
          <li>
             <span><%= key %></span>
             <span><%= item.name %></span>
             <span><%= item.type %></span>
           </li>
       <% }); %>
   </script>

This is html

<div>
  <ul id="list_2"></ul>
</div>

This is the javascript code which contains json object and putting template into html

   var items = [
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       } 
   ];
  $(document).ready(function(){
      var template = $("#template_1").html();
      $("#list_2").html(_.template(template,{items:items}));
  });

静赏你的温柔 2024-10-20 17:43:09

有了快递就这么简单。您所需要的只是在节点上使用 consolidate 模块,因此您需要安装它:

npm install consolidate --save

然后您应该通过以下方式将默认引擎更改为 html 模板:

app.set('view engine', 'html');

为 html 扩展注册下划线模板引擎:

app.engine('html', require('consolidate').underscore);

它是完毕 !

现在加载例如名为“index.html”的模板:

res.render('index', { title : 'my first page'});

也许您需要安装下划线模块。

npm install underscore --save

我希望这对您有帮助!

with express it's so easy. all what you need is to use the consolidate module on node so you need to install it :

npm install consolidate --save

then you should change the default engine to html template by this:

app.set('view engine', 'html');

register the underscore template engine for the html extension:

app.engine('html', require('consolidate').underscore);

it's done !

Now for load for example an template called 'index.html':

res.render('index', { title : 'my first page'});

maybe you will need to install the underscore module.

npm install underscore --save

I hope this helped you!

夏见 2024-10-20 17:43:09

我想分享一项更重要的发现。

使用 <%= 变量 =>会导致跨站点脚本漏洞。所以使用<%-变量->比较安全反而。

我们必须将 <%= 替换为 <%- 以防止跨站点脚本攻击。不确定,这是否会对性能产生影响

I wanted to share one more important finding.

use of <%= variable => would result in cross-site scripting vulnerability. So its more safe to use <%- variable -> instead.

We had to replace <%= with <%- to prevent cross-site scripting attacks. Not sure, whether this will it have any impact on the performance

国际总奸 2024-10-20 17:43:09

洛达什也是一样
首先写一个脚本如下:

<script type="text/template" id="genTable">
<table cellspacing='0' cellpadding='0' border='1'>
        <tr>
            <% for(var prop in users[0]){%>
            <th><%= prop %> </th>
            <% }%>
        </tr>
        <%_.forEach(users, function(user) { %>
            <tr>
                 <% for(var prop in user){%>
                    <td><%= user[prop] %> </td>
                <% }%>

            </tr>
        <%})%>
</table>

现在写一些简单的JS如下:

var arrOfObjects = [];
for (var s = 0; s < 10; s++) {
    var simpleObject = {};
    simpleObject.Name = "Name_" + s;
    simpleObject.Address = "Address_" + s;
    arrOfObjects[s] = simpleObject;
}
var theObject = { 'users': arrOfObjects }
var compiled = _.template($("#genTable").text());
var sigma = compiled({ 'users': myArr });

$(sigma).appendTo("#popup");

其中popoup是你要生成表格的div

Lodash is also the same
First write a script as follows:

<script type="text/template" id="genTable">
<table cellspacing='0' cellpadding='0' border='1'>
        <tr>
            <% for(var prop in users[0]){%>
            <th><%= prop %> </th>
            <% }%>
        </tr>
        <%_.forEach(users, function(user) { %>
            <tr>
                 <% for(var prop in user){%>
                    <td><%= user[prop] %> </td>
                <% }%>

            </tr>
        <%})%>
</table>

Now write some simple JS as follows:

var arrOfObjects = [];
for (var s = 0; s < 10; s++) {
    var simpleObject = {};
    simpleObject.Name = "Name_" + s;
    simpleObject.Address = "Address_" + s;
    arrOfObjects[s] = simpleObject;
}
var theObject = { 'users': arrOfObjects }
var compiled = _.template($("#genTable").text());
var sigma = compiled({ 'users': myArr });

$(sigma).appendTo("#popup");

Where popoup is a div where you want to generate the table

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文