# \_.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>

![](/files/-MiCP_HSyXpYI6Cwn1I1)

![](/files/-MiCPQALgBYgLMW7WMmA)

```
<!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ả

![](/files/-MiCJseSFQz3JENMqstx)

```
<!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

![](/files/-MiCN1IqE-tjskNDwnBj)

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;
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://javascriptuse.gitbook.io/javascript/_.template-underscorejs-templates-1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
