---
description: https://theshravan.net/blog/how-to-use-underscorejs-templates/
---

# \_.template, UnderscoreJS Templates Full (ok)

### &#x20;_**Syntax:**_

```
_.template(templateString, settings)
```

```
templateString: Một chuỗi chứa mẫu sẽ được hiển thị.
settings(optional): Hàm băm chứa bất kỳ _.templateSettings nào cần được ghi đè.
```

### _Giá trị trả về: Hàm \_.template trả về một hàm có các biến được chỉ định trong mẫu làm tham số của nó._

```
<% mã javascript thực thi%>
<% = giá trị được in%>
<% - Giá trị thoát HTML sẽ được in%>
```

> Chú ý: Hai cách viết này có kết quả như nhau :))
>
> [https://stackoverflow.com/questions/4778881/how-to-use-underscore-js-as-a-template-engine](https://stackoverflow.com/questions/4778881/how-to-use-underscore-js-as-a-template-engine)

![](https://2494213435-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LYjAG13rAPdbArSfRyB%2F-MiCNzgvCFkZveL16I9a%2F-MiCP_HSyXpYI6Cwn1I1%2FScreenshot_3.png?alt=media\&token=dae77896-9088-4757-8757-50ec98162fcc)

![](https://2494213435-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LYjAG13rAPdbArSfRyB%2F-MiCNzgvCFkZveL16I9a%2F-MiCPQALgBYgLMW7WMmA%2FScreenshot_4.png?alt=media\&token=ba519403-9cdc-4e0e-a39f-6ef0334740aa)

```
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="jquery.js"></script>
  <script src="underscore.js"></script>
  <title>Document</title>
</head>
<body>
  <!-- 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();

    var result  = _.template(template)({items:items});

    var result  = _.template(template,{items:items});
    
    $("#target").html(result);
  </script>
</body>
</html>
```

### Ví dụ 1: Hiển thị nội tuyến kết quả

![](https://2494213435-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LYjAG13rAPdbArSfRyB%2F-MiCH6e3NhlYdGft5sPv%2F-MiCJseSFQz3JENMqstx%2FScreenshot_1.png?alt=media\&token=2a9d10ec-460c-48ec-91df-c8e262f78229)

```
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="jquery.js"></script>
  <script src="underscore.js"></script>
  <title>Document</title>
</head>
<body>
  <div id='output'></div>
  <script>
    window.onload = function() {
      var person = {
          name: 'Shravan Kumar'
      };
      var result = _.template('Name: <%= name %>')(person);
      var outputDiv = document.querySelector('#output');
      outputDiv.innerHTML = result;
    };
  </script>
</body>
</html>
```

### Ví dụ 2: Hiển thị nội tuyến kết quả thoát html

![](https://2494213435-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LYjAG13rAPdbArSfRyB%2F-MiCJv3IW1YLwW9s3Sqq%2F-MiCN1IqE-tjskNDwnBj%2FScreenshot_2.png?alt=media\&token=5384e5ca-b4dc-4edf-b58c-691d08cf2c54)

C:\xampp\htdocs\html\index.html

```
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="jquery.js"></script>
  <script src="underscore.js"></script>
  <title>Document</title>
</head>
<body>
  <div id="output"></div>
  <script id="sample-template" type="text/html">
    <p>
      Latitude: <%= latitude %>
    </p>
    <p>
      Longitude: <%= longitude %>
    </p>
    <% var numbers = [1, 2, 3, 4, 5]; %>
    <ul>
      <% _(numbers).each(function(number) { %>
        <li>
          <%= number %>
        </li>
      <% }); %>
    </ul>
    <p>HTML escaped output: <%=htmlContent%> </p>
  </script>
  <script src="script.js"></script>
</body>
</html>
```

C:\xampp\htdocs\html\script.js

```
var data = {
  latitude: 20.2,
  longitude: 30.5,
  htmlContent: '<div class="title">This <span>UnderscoreJs Templating</span> Example</div>'
};
var templateSelector = document.querySelector('#sample-template').innerHTML;
var result = _.template(templateSelector)(data);
var outputDiv = document.querySelector("#output");
outputDiv.innerHTML = result;
```
