<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                {% raw %} # JavaScript Mustache 教程 > 原文: [http://zetcode.com/javascript/mustache/](http://zetcode.com/javascript/mustache/) 在 JavaScript Mustache 教程中,我們展示了如何使用 Mustache 模板引擎。 ## Mustache Mustache 是一個簡單的 Web 模板系統。 它可用于許多編程語言,包括 JavaScript 和 Java。 Mustache 被描述為一種無邏輯的模板引擎,因為它沒有任何明確的控制流語句,例如`if`和`else`條件語句或`for`循環。 可以使用節標記處理列表和 lambda 來實現循環和條件評估。 JSON(JavaScript 對象表示法)是一種輕量級的數據交換格式。 人類很容易讀寫,機器也很容易解析和生成。 `application/json`是 JSON 的官方 Internet 媒體類型。 JSON 文件擴展名是`.json`。 jQuery 是一個 JavaScript 庫,用于處理 DOM。 使用 jQuery,我們可以查找,選擇,遍歷和操作 HTML 文檔的各個部分。 ```js <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.min.js"></script> ``` Mustache 是??一個 JavaScript 庫,可以從 CDN(內容交付網絡)引用。 ## Mustache 基本模板示例 在第一個示例中,我們有一個基本的模板示例。 `basic.html` ```js <!DOCTYPE html> <html lang="en"> <head> <title>JavaScript Mustache template</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.min.js"></script> </head> <body> <div id="mypanel"></div> <button id="btn">Load</button> <script> $("#btn").on('click', function() { var data = { name: "Jonathan" }; var template = "Hello {{ name }}"; var text = Mustache.render(template, data); $("#mypanel").html(text); }); </script> </body> </html> ``` 單擊該按鈕,我們會在頁面上寫一條消息。 ```js <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.min.js"></script> ``` 在示例中,我們使用 JQuery 和 Mustache JavaScript 庫。 ```js $("#btn").on('click', function() { ... } ``` 我們創建一個對按鈕單擊事件做出反應的處理器。 ```js var data = { name: "Jonathan" }; ``` 這是數據。 ```js var template = "Hello {{ name }}"; ``` 這是 Moustache 模板。 `{{ name }}`是一個 Moustache 標簽,已被數據值替換。 ```js var text = Mustache.render(template, data); ``` 最終輸出使用`Mustache.render()`函數渲染。 模板引擎將模板與數據連接起來以生成輸出。 ```js $("#mypanel").html(text); ``` 呈現的文本將被寫入面板元素。 ## Mustache 使用模板標簽 在第二個示例中,我們使用模板標記。 當前使用的是`<script type="text/template">`,但是在不久的將來它將被`<template>`標簽取代。 標記包含客戶端內容,該內容不會在加載頁面時呈現,而是在運行時使用 JavaScript 實例化。 `json_url.html` ```js <!DOCTYPE html> <html lang="en"> <head> <title>JavaScript Mustache template</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.min.js"></script> </head> <body> <script id="mp_template" type="text/template"> Date: {{ time }} <br> Time: {{ date }} <br> Unix time: {{ milliseconds_since_epoch }} </script> <div id="mypanel"></div> <button id="btn">Load</button> <script> $(function() { $("#btn").on('click', function() { $.getJSON('http://time.jsontest.com', function(data) { var template = $("#mp_template").html(); var text = Mustache.render(template, data); $("#mypanel").html(text); }); }); }); </script> ``` 在此示例中,我們向`time.jsontest.com`發送請求,該請求返回具有三個屬性的 JSON 響應:`time`,`date`和`milliseconds_since_epoch`(Unix 時間)。 ```js <script id="mp_template" type="text/template"> Date: {{ time }} <br> Time: {{ date }} <br> Unix time: {{ milliseconds_since_epoch }} </script> ``` 我們在`<script id="mp_template" type="text/template">`標簽內定義模板。 ```js $.getJSON('http://time.jsontest.com', function(data) { ``` 使用`$.getJSON()`,我們使用 GET HTTP 請求從服務器加載 JSON 編碼的數據。 ```js var template = $("#mp_template").html(); ``` 使用 JQuery 的`html()`方法,我們可以獲得模板數據。 ```js var text = Mustache.render(template, data); ``` 輸出使用`Mustache.render()`呈現。 ```js $("#mypanel").html(text); ``` 最終文本將寫入面板元素。 ## 帶有 Java Servlet 的 Mustache 在第三個示例中,我們使用 servlet 創建一個 Java Web 應用。 ```js $ tree . ├── pom.xml └── src ├── main │ ├── java │ │ └── com │ │ └── zetcode │ │ ├── bean │ │ │ └── City.java │ │ └── web │ │ └── GetCities.java │ └── webapp │ ├── index.html │ ├── META-INF │ │ └── context.xml │ └── WEB-INF └── test └── java ``` 這是項目結構。 `pom.xml` ```js <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zetcode</groupId> <artifactId>ServletJsonMustache</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>ServletJsonMustache</name> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.0</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.3</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project> ``` 這是 Maven POM 文件。 我們有兩個工件:用于 Java servlet 的`javax.servlet-api`和用于 Java JSON 處理的`gson`。 `context.xml` ```js <?xml version="1.0" encoding="UTF-8"?> <Context path="/ServletJsonMustache"/> ``` 在 Tomcat `context.xml`文件中,我們定義了上下文路徑。 它是 Web 應用的名稱。 `City.java` ```js package com.zetcode.bean; public class City { private Long id; private String name; private int population; public City() { } public City(Long id, String name, int population) { this.id = id; this.name = name; this.population = population; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPopulation() { return population; } public void setPopulation(int population) { this.population = population; } @Override public String toString() { return "City{" + "id=" + id + ", name=" + name + ", population=" + population + '}'; } } ``` 這是`City` bean。 它具有三個屬性:id,名稱和人口。 `GetCities.java` ```js package com.zetcode.web; import com.google.gson.Gson; import com.zetcode.bean.City; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(name = "GetCities", urlPatterns = {"/GetCities"}) public class GetCities extends HttpServlet { private static final List<City> cities; static { cities = new ArrayList<>(); cities.add(new City(1L, "Bratislava", 432000)); cities.add(new City(2L, "Budapest", 1759000)); cities.add(new City(3L, "Prague", 1280000)); cities.add(new City(4L, "Warsaw", 1748000)); cities.add(new City(5L, "Los Angeles", 3971000)); cities.add(new City(6L, "New York", 8550000)); cities.add(new City(7L, "Edinburgh", 464000)); cities.add(new City(8L, "Berlin", 3671000)); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json;charset=UTF-8"); try (ServletOutputStream os = response.getOutputStream()) { os.print(new Gson().toJson(cities)); } } } ``` 這是`GetCities` servlet。 ```js response.setContentType("application/json;charset=UTF-8"); ``` 響應對象的內容類型設置為`application/json`。 ```js try (ServletOutputStream os = response.getOutputStream()) { os.print(new Gson().toJson(cities)); } ``` 我們使用`Gson`庫將 Java 列表轉換為 JSON 數組。 將該數組寫入響應輸出流。 數組未命名。 `index.html` ```js <!DOCTYPE html> <html> <head> <title>Cities</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.min.js"></script> </head> <body> <script id="mp_template" type="text/template"> <table> <thead> <tr> <th>Id</th> <th>Name</th> <th>Price</th> </tr> </thead> <tbody> {{#.}} <tr> <td>{{id}}</td> <td>{{name}}</td> <td>{{population}}</td> </tr> {{/.}} </tbody> </table> </script> <div id="mypanel"></div> <button id="btn">Load</button> <script> $(function () { $("#btn").on('click', function () { $.getJSON('http://localhost:8084/ServletJsonMustache/GetCities', function (cities) { var template = $("#mp_template").html(); var text = Mustache.render(template, cities); $("#mypanel").html(text); }); }); }); </script> </body> </html> ``` 這是主頁。 ```js <script id="mp_template" type="text/template"> ... </script> ``` 胡子模板放置在`<script id="mp_template" type="text/template">`標簽中。 ```js <tbody> {{#.}} <tr> <td>{{id}}</td> <td>{{name}}</td> <td>{{population}}</td> </tr> {{/.}} </tbody> ``` 使用`{{#.}} {{/.}}`語法,我們遍歷了 servlet 返回的未命名 JSON 數組,并用值替換了 Mustache 標簽。 ```js $.getJSON('http://localhost:8084/ServletJsonMustache/GetCities', function (cities) { ``` 使用`$.getJSON()`,我們稱為`GetCities` Servlet。 該 Servlet 返回 JSON 數據,并使用 Mustache 處理。 ### 命名 JSON 數組 如果我們想命名返回的 JSON 數組,可以使用以下代碼: ```js Gson gson = new GsonBuilder().create(); JsonArray jarray = gson.toJsonTree(cities).getAsJsonArray(); JsonObject jsonObject = new JsonObject(); jsonObject.add("cities", jarray); os.print(jsonObject.toString()); ``` 在 Servlet 中,我們將 JSON 數組放入另一個 JSON 對象中,并將屬性命名為`cities`。 ```js <tbody> {{#cities}} <tr> <td>{{id}}</td> <td>{{name}}</td> <td>{{population}}</td> </tr> {{/cities}} </tbody> ``` 在 Mustache 模板中,我們使用以下語法:`{{#cities}} {{/cities}}`。 ![Rendering JSON data from Servlet with Mustache](https://img.kancloud.cn/cc/36/cc36a1ad31e48b92a10b8f5981d3226c_590x372.jpg) 圖:使用 Mustache 從 Servlet 渲染JSON數據 在本教程中,我們使用了 Mustache 模板引擎。 您可能也對以下相關教程感興趣: [JSON 服務器教程](/javascript/jsonserver/),[從 JavaScript 中的 URL 讀取 JSON](/articles/javascriptjsonurl/) , [JQuery 教程](/web/jquery/), [Node.js 教程](/javascript/nodejs/) 或 [jQuery 自動完成教程](/articles/jqueryautocomplete/)或[使用 jQuery `DatePicker`](/articles/jquerydatepicker/) 。 {% endraw %}
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看