簡體   English   中英

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

[英]How to use underscore.js as a template engine?

我正在嘗試了解javascript作為服務器端語言和函數式語言的新用法。 幾天前我聽說過node.js和表達框架。 然后我看到underscore.js作為一組實用函數。 在stackoverflow上看到了這個問題 它說我們可以使用underscore.js作為模板引擎。 任何人都知道有關如何使用underscore.js進行模板化的好教程,特別是對於那些對高級javascript經驗較少的biginners。 謝謝

您需要了解的關於下划線模板的所有內容都在這里 只需記住3件事:

  1. <% %> - 執行一些代碼
  2. <%= %> - 在模板中打印一些值
  3. <%- %> - 打印一些HTML轉義的值

這就是它的全部。

簡單的例子:

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

那么tpl({foo: "blahblah"})將呈現給字符串<h1>Some text: blahblah</h1>

<!-- 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列表按第一個字母(復雜的例子w /圖像,函數調用,子模板)分組! 盡情狂歡...
  • 下面是@tarun_telang注意到的XSS hack的JsFiddle演示
  • JsFiddle一個非標准方法來做子模板

在它最簡單的形式,你會使用它:

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>');

模板的文檔是部分的,我看了源。

_.template函數有3個參數:

  1. 字符串文本 :模板字符串
  2. 對象數據 :評估數據
  3. 對象設置 :本地設置, _. trylateSettings是全局設置對象

如果沒有給出數據 (或null),則返回渲染函數。 它有一個參數:

  1. 對象數據 :與上面的數據相同

設置中有3個正則表達式模式和1個靜態參數:

  1. RegExp 評估 :模板字符串中的“<%code%>”
  2. RegExp 插值 :模板字符串中的“<%= code%>”
  3. RegExp 轉義 :“<% - code%>”
  4. 字符串變量 :可選,模板字符串中數據參數的名稱

將簡單評估評估部分中的代碼。 您可以使用__p + =“mystring”命令將此部分中的字符串添加到已評估的模板中,但不建議這樣做(不是模板界面的一部分),請使用插值部分而不是它。 此類型的部分用於向模板添加if或for等塊。

插值部分中的代碼結果將添加到評估的模板中。 如果返回null,則添加空字符串。

轉義部分使用_.escape對給定代碼的返回值轉義html。 因此其類似比在插值部的_.escape(代碼),但它與\\的空白字符等\\逸出ñ它傳遞代碼到_.escape之前。 我不知道為什么這很重要,它在代碼中,但它適用於插值_.escape - 它也不會逃避空白字符。

默認情況下, data參數由with(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);

結果

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()函數,或者您可以使用require.jstpl插件從單獨的文件加載它。

使用簡潔而不是模板來構建dom樹的另一種選擇。

我給出一個非常簡單的例子

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}));
  });

表達它很容易。 您需要的只是在節點上使用合並模塊,因此您需要安裝它:

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

我希望這對你有所幫助!

我想分享一個更重要的發現。

使用<%= variable =>會導致跨站點腳本漏洞。 因此,使用<% - variable - >更安全。

我們不得不將<%=替換為<% - 以防止跨站點腳本攻擊。 不確定,這是否會對性能產生任何影響

Lodash也是一樣的首先寫一個腳本如下:

<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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM