目前前端主流的開發框架有Vue、React以及Angular等,但是依然有一部分開發人員并不會去使用這些框架,特別是一些偏向后端的開發者,可能依然在使用類似于jquery+Bootstrap的方式在開發一些項目,而且有些項目可能傳統的方式更加合適,因此JavaScript前端模板引擎就能夠發會很大作用了,那么今天就介紹10大開源模板引擎,依據不同的場景或者功能特性,可以選擇不同的模板引擎應用到項目中去:
Art-template是一個簡單且超快速的模板引擎,可通過范圍預先聲明的技術優化模板渲染速度。它實現了接近JavaScript極限的運行時性能。同時,它支持NodeJS和瀏覽器。
https://github.com/aui/art-template var template = require('art-template'); var html = template(__dirname + '/tpl-user.art', { user: { name: 'aui' } });
為了最快,最簡潔的JavaScript模板功能,重點是在V8和Nodejs下的性能。它對Node.js和瀏覽器均顯示出出色的性能。doT.js快速,小巧且沒有依賴性。
https://github.com/olado/doTHi {{=it.name}}!{{=it.age || ''}}
快速且強大的JavaScript模板引擎,零依賴。與node.js之類的服務器端環境,RequireJS之類的模塊加載器以及所有Web瀏覽器兼容。
https://github.com/blueimp/JavaScript-Templates <script type="text/x-tmpl" id="tmpl-demo">{%=o.title%}
Released under the {%=o.license.name%}.
Features
JavaScript模板引擎,簡單易用,支持webpack和fis。提供了一組模板語法,用戶可以編寫一個模板塊。每次傳入數據時,生成由相應數據生成的HTML片段,呈現不同的效果。
https://github.com/yanhaijing/template.js const data = { list: [ {name: "yan"}, {name: "haijing"} ] };
Tempo是一個簡單,直觀的JavaScript渲染引擎,能夠以純HTML格式制作數據模板。關注點分離:JavaScript文件中沒有HTML,HTML中也沒有JavaScript;輕松處理AJAX / JSON內容,可在Safari,Chrome,FireFox,Opera和Internet Explorer 6+中運行
https://github.com/twigkit/tempo
聲稱具有嵌入式CoffeeScript語法的最快的JavaScript模板引擎。具有出色的性能,模板緩存,自動重新加載已更改的模板和模板中的CoffeeScript代碼
https://github.com/baryshev/ect var ECT = require('ect'); var renderer = ECT({ root : __dirname + '/views', ext : '.ect' }); renderer.render('page', { title: 'Hello, World!' }, function (error, html) { console.log(error); console.log(html); });
.dom從React.js借用了一些概念(例如可重用的組件和虛擬DOM),并嘗試利用ES6 javascript功能以最小的占用空間復制它們。該庫的大小不超過512個字節。正在大力利用ES6規范。
https://github.com/wavesoft/dot-dom function Clickable(props, state, setState) { const {clicks=0} = state; return H('button', { onclick() { setState({clicks: clicks+1}) } }, `Clicked ${clicks} times` ); } R( H('div', H(Clickable), H(Clickable) ), document.body )
Template7是第一個具有類似Handlebars語法的移動優先JavaScript模板引擎。它在Framework7中用作默認模板引擎。它是超輕量級的(縮小并壓縮成1KB左右)并且運行迅速(比mobile Safari中的Handlebars快2-3倍)。
https://github.com/nolimits4web/template7{{#each items}}
- {{/each}}
{{title}}
BunnyJS是現代的原生JS和ES6庫以及下一代前端框架,無依賴性的小型獨立組件的軟件包。它沒有依賴性-可以隨時隨地在任何項目中使用
https://github.com/Mevrael/bunny import { Component as BunnyComponent } from 'bunnyjs/src/...'; export const Component = Object.assign({}, BunnyComponent, { init(arg) { // do whatever you want console.log(arg); // call default (parent) return BunnyComponent.init(arg); } });
Squirrelly是使用JavaScript實現的現代,可配置且功能強大的快速模板引擎。它在ExpressJS開箱即用,完整版壓縮后僅約2.2KB。
https://github.com/squirrellyjs/squirrelly var myTemplate = "My favorite kind of cake is: {{favoriteCake}}
" Sqrl.Render(myTemplate, {favoriteCake: 'Chocolate!'}) // Returns: 'My favorite kind of cake is: Chocolate!
{{if(options.somevalue === 1)}} Display this {{#else}} Display this {{/if}} {{each(options.somearray)}} Display this The current array element is {{@this}} The current index is {{@index}} {{/each}}
Javascript的模板引擎相對較多,從性能、簡單性、易用性等方面會有所不同,開發者們可以根據不同的角度去選擇一個合適的模板引擎用于項目研發或者重構,Enjoy it!
目前前端主流的開發框架有Vue、React以及Angular等,但是依然有一部分開發人員并不會去使用這些框架,特別是一些偏向后端的開發者,可能依然在使用類似于jquery+Bootstrap的方式在開發一些項目,而且有些項目可能傳統的方式更加合適,因此JavaScript前端模板引擎就能夠發會很大作用了,那么今天就介紹10大開源模板引擎,依據不同的場景或者功能特性,可以選擇不同的模板引擎應用到項目中去:
Art-template是一個簡單且超快速的模板引擎,可通過范圍預先聲明的技術優化模板渲染速度。它實現了接近JavaScript極限的運行時性能。同時,它支持NodeJS和瀏覽器。
https://github.com/aui/art-template var template = require('art-template'); var html = template(__dirname + '/tpl-user.art', { user: { name: 'aui' } });
為了最快,最簡潔的JavaScript模板功能,重點是在V8和Nodejs下的性能。它對Node.js和瀏覽器均顯示出出色的性能。doT.js快速,小巧且沒有依賴性。
https://github.com/olado/doTHi {{=it.name}}!{{=it.age || ''}}
快速且強大的JavaScript模板引擎,零依賴。與node.js之類的服務器端環境,RequireJS之類的模塊加載器以及所有Web瀏覽器兼容。
https://github.com/blueimp/JavaScript-Templates <script type="text/x-tmpl" id="tmpl-demo">{%=o.title%}
Released under the {%=o.license.name%}.
Features
JavaScript模板引擎,簡單易用,支持webpack和fis。提供了一組模板語法,用戶可以編寫一個模板塊。每次傳入數據時,生成由相應數據生成的HTML片段,呈現不同的效果。
https://github.com/yanhaijing/template.js const data = { list: [ {name: "yan"}, {name: "haijing"} ] };
Tempo是一個簡單,直觀的JavaScript渲染引擎,能夠以純HTML格式制作數據模板。關注點分離:JavaScript文件中沒有HTML,HTML中也沒有JavaScript;輕松處理AJAX / JSON內容,可在Safari,Chrome,FireFox,Opera和Internet Explorer 6+中運行
https://github.com/twigkit/tempo
聲稱具有嵌入式CoffeeScript語法的最快的JavaScript模板引擎。具有出色的性能,模板緩存,自動重新加載已更改的模板和模板中的CoffeeScript代碼
https://github.com/baryshev/ect var ECT = require('ect'); var renderer = ECT({ root : __dirname + '/views', ext : '.ect' }); renderer.render('page', { title: 'Hello, World!' }, function (error, html) { console.log(error); console.log(html); });
.dom從React.js借用了一些概念(例如可重用的組件和虛擬DOM),并嘗試利用ES6 javascript功能以最小的占用空間復制它們。該庫的大小不超過512個字節。正在大力利用ES6規范。
https://github.com/wavesoft/dot-dom function Clickable(props, state, setState) { const {clicks=0} = state; return H('button', { onclick() { setState({clicks: clicks+1}) } }, `Clicked ${clicks} times` ); } R( H('div', H(Clickable), H(Clickable) ), document.body )
Template7是第一個具有類似Handlebars語法的移動優先JavaScript模板引擎。它在Framework7中用作默認模板引擎。它是超輕量級的(縮小并壓縮成1KB左右)并且運行迅速(比mobile Safari中的Handlebars快2-3倍)。
https://github.com/nolimits4web/template7{{#each items}}
- {{/each}}
{{title}}
BunnyJS是現代的原生JS和ES6庫以及下一代前端框架,無依賴性的小型獨立組件的軟件包。它沒有依賴性-可以隨時隨地在任何項目中使用
https://github.com/Mevrael/bunny import { Component as BunnyComponent } from 'bunnyjs/src/...'; export const Component = Object.assign({}, BunnyComponent, { init(arg) { // do whatever you want console.log(arg); // call default (parent) return BunnyComponent.init(arg); } });
Squirrelly是使用JavaScript實現的現代,可配置且功能強大的快速模板引擎。它在ExpressJS開箱即用,完整版壓縮后僅約2.2KB。
https://github.com/squirrellyjs/squirrelly var myTemplate = "My favorite kind of cake is: {{favoriteCake}}
" Sqrl.Render(myTemplate, {favoriteCake: 'Chocolate!'}) // Returns: 'My favorite kind of cake is: Chocolate!
{{if(options.somevalue === 1)}} Display this {{#else}} Display this {{/if}} {{each(options.somearray)}} Display this The current array element is {{@this}} The current index is {{@index}} {{/each}}
Javascript的模板引擎相對較多,從性能、簡單性、易用性等方面會有所不同,開發者們可以根據不同的角度去選擇一個合適的模板引擎用于項目研發或者重構,Enjoy it!
者:liuxiaopeng
鏈接:https://www.cnblogs.com/paddix/p/8905531.html
雖然現在很多開發,都采用了前后端完全分離的模式,即后端只提供數據接口,前端通過AJAX請求獲取數據,完全不需要用到模板引擎。這種方式的優點在于前后端完全分離,并且隨著近幾年前端工程化工具和MVC框架的完善,使得這種模式的維護成本相對來說也更加低一點。但是這種模式不利于SEO,并且在性能上也會稍微差一點,還有一些場景,使用模板引擎會更方便,比如說郵件模板。這篇文章主要討論Spring boot與模板引擎Thymeleaf、Freemaker以及JSP的集成。
第一步:引入jar包(thymeleaf對應的starter):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
第二步:配置thymeleaf:
spring:
thymeleaf:
prefix: classpath:/templates/
check-template-location: true
cache: false
suffix: .html
encoding: UTF-8
content-type: text/html
mode: HTML5
prefix:指定模板所在的目錄
check-tempate-location: 檢查模板路徑是否存在
cache: 是否緩存,開發模式下設置為false,避免改了模板還要重啟服務器,線上設置為true,可以提高性能。
encoding&content-type:這個大家應該比較熟悉了,與Servlet中設置輸出對應屬性效果一致。
mode:這個還是參考官網的說明吧,并且這個是2.X與3.0不同,本文自動引入的包是2.15。
第三步 編寫thymeleaf模板文件:
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta content="text/html;charset=UTF-8"/>
</head>
<body>
<h6>Thymeleaf 模板引擎</h6>
<table border="1" bgcolor="#f0ffff">
<thead>
<tr>
<th>序號</th>
<th>標題</th>
<th>摘要</th>
<th>創建時間</th>
</tr>
</thead>
<tbody th:each="article : ${list}">
<tr>
<td th:text="${article.id}"></td>
<td th:text="${article.title}"></td>
<td th:text="${article.summary}"></td>
<td th:text="${article.createTime}"></td>
</tr>
</tbody>
</table>
</body>
</html>
大家可以看到,thymeleaf還是比較簡單的,并且最大的特點就是的標簽是作為HTML元素的屬性存在的,也就是說,該頁面是可以直接通過瀏覽器來預覽的,只是沒有數據而已,這個很方便大家進行調試。
第四步 配置Controller:
@Controller
@RequestMapping("/article")
public class ArticleController {
@Autowired
private ArticleService articleService;
@RequestMapping("/articleList.html")
public String getArticleList(Model model, String title, @RequestParam(defaultValue = "10") Integer pageSize,
@RequestParam(defaultValue = "1") Integer pageNum) {
int offset = (pageNum - 1) * pageSize;
List<Article> list = articleService.getArticles(title, 1L, offset, pageSize);
model.addAttribute("list", list);
return "article/articleList";
}
}
注意,這里用的注解是@Controller,而不是@RestController,因為@RestController會自動將返回結果轉為字符串。
第五步 查看結果
1、引入jar包(Freemarker對應的starter)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2、配置freemarker:
spring:
freemarker:
template-loader-path: classpath:/templates/
suffix: .ftl
content-type: text/html
charset: UTF-8
settings:
number_format: '0.##'
除了settings外,其他的配置選項和thymeleaf類似。settings會對freemarker的某些行為產生影響,如日期格式化,數字格式化等,感興趣的同學可以參考官網提供的說明:https://freemarker.apache.org/docs/api/freemarker/template/Configuration.html#setSetting-java.lang.String-java.lang.String-
3、編寫freemarker模板文件:
<html>
<title>文章列表</title>
<body>
<h6>Freemarker 模板引擎</h6>
<table border="1">
<thead>
<tr>
<th>序號</th>
<th>標題</th>
<th>摘要</th>
<th>創建時間</th>
</tr>
</thead>
<#list list as article>
<tr>
<td>${article.id}</td>
<td>${article.title}</td>
<td>${article.summary}</td>
<td>${article.createTime?string('yyyy-MM-dd hh:mm:ss')}</td>
</tr>
</#list>
</table>
</body>
</html>
4、編寫Controller:
@Controller
@RequestMapping("/article")
public class ArticleController {
@Autowired
private ArticleService articleService;
@RequestMapping("/list.html")
public String getArticles(Model model, String title, @RequestParam(defaultValue = "10") Integer pageSize, Integer pageNum) {
if (pageSize == null) {
pageSize = 10;
}
if (pageNum == null) {
pageNum = 1;
}
int offset = (pageNum - 1) * pageSize;
List<Article> list = articleService.getArticles(title, 1L, offset, pageSize);
model.addAttribute("list", list);
return "article/list";
}
}
5、訪問頁面:
在正式的項目開發中,現在已經極少用jsp模板了,所以Spring boot對jsp的支持也不是很好,因此配置起來比thymeleaf和Freemaker相對來說就更復雜一點。
第一步 引入jar包:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
第一個jstl的依賴用于支持el表達式,第二個依賴用于支持jsp。注意,如果是在外部的tomcat中運行,需要將scope設置為provide,防止jar包沖突。
第二步 手動創建webapp目錄:
需要手動在main目錄下創建一個webapp的目錄,結構如下:
第三步 jsp路勁配置:
在application.yml中添加如下配置:
spring:
mvc:
view:
prefix: /WEB-INF/jsp/
suffix: .jsp
了解Spring mvc的應該很熟悉上面的配置。
第四步 編寫jsp頁面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Title</title>
</head>
<body>
<table border="1">
<c:forEach var="article" items="${list}">
<tr>
<td>${article.id}</td>
<td>${article.title}</td>
<td>${article.summary}</td>
<td>${article.createTime}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
第五步 編寫Controller:
@RequestMapping("/listJsp")
public String getArticleListJsp(Model model, String title, @RequestParam(defaultValue = "10") Integer pageSize, Integer pageNum) {
if (pageSize == null) {
pageSize = 10;
}
if (pageNum == null) {
pageNum = 1;
}
int offset = (pageNum - 1) * pageSize;
List<Article> list = articleService.getArticles(title, 1L, offset, pageSize);
model.addAttribute("list", list);
return "articles";
}
第六步 訪問結果頁面:
總體來講,Spring boot對thymeleaf和Freemaker支持比較友好,配置相對也簡單一點,在實際的開發中,大多也以這兩種模板引擎為主,很少有用jsp的,jsp現在可能更多是在實驗或者學習階段使用。jsp配置比較麻煩一點的事情是不像前兩者,網上的說法基本一致,但是對Jsp的配置有很多種說法,比如說是不是需要將jar包改成war包?jsp的依賴是否需要設置為provide等等,這個主要依賴于你是否最后要將程序部署到外部的tomcat還是直接運行jar?因為本文都是直接在idea下直接運行Application類,所以這些操作就不需要了。
*請認真填寫需求信息,我們會在24小時內與您取得聯系。