FrankKai / FrankKai.github.io

FE blog
https://frankkai.github.io/
363 stars 39 forks source link

一些好用的模板引擎库 #143

Open FrankKai opened 5 years ago

FrankKai commented 5 years ago

模板引擎,从前端的角度看,主要作用于HTML、JS,或者说是vue,react,angular中的{{ ... }},但其实这是一种很狭隘的认识。 因为模板引擎,不仅仅在前端有应用,在配置文件、源代码,同一个模板引擎,也有多种语言的实现,可以应用在不同的语言中。 但是这篇文章还是主要讲前端、node端常用的一些模板引擎库。

由于缺少react、angular的实践,因此就没有罗列。

FrankKai commented 5 years ago

vue.js

<template>
  <div>
    <p>{{name}}</p>
    <p v-once>{{age}}</p>
    <p>{{rawHtml}}</p>
    <p v-html="rawHtml"></p>
    <p>{{ok ? 'YES' : 'NO'}}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      name: 'Kai',
      age: 24,
      rawHtml: '<span style="color: red">This should be red.</span>',
      ok: true,
    };
  },
};
</script>

输出:

<div>
    <p>Kai</p> 
    <p>24</p> 
    <p>&lt;span style="color: red"&gt;This should be red.&lt;/span&gt;</p>
    <p>
        <span style="color: red">This should be red.</span>
    </p>
    <p>YES</p>
</div>
FrankKai commented 5 years ago

pug

doctype html
html(lang="en")
  head
    title= pageTitle
    script(type='text/javascript').
      if (foo) bar(1 + 5)
  body
    h1 Pug - node template engine
    #container.col
      if youAreUsingPug
        p You are amazing
      else
        p Get on it!
      p.
        Pug is a terse and simple templating language with a
        strong focus on performance and powerful features.
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Pug</title>
    <script type="text/javascript">
      if (foo) bar(1 + 5)
    </script>
  </head>
  <body>
    <h1>Pug - node template engine</h1>
    <div id="container" class="col">
      <p>You are amazing</p>
      <p>Pug is a terse and simple templating language with a strong focus on performance and powerful features.</p>
    </div>
  </body>
</html>
FrankKai commented 5 years ago

mustache.js

var mustache = require("mustache")
var view = {
  title: "Joe",
  calc: function () {
    return 2 + 4;
  }
};
var output = mustache.render("{{title}} spends {{calc}}", view);

输出: "Joe spends 6"

FrankKai commented 5 years ago

underscore.js

const _ = require("underscore")
const compiled = _.template("hello: <%= name %>");
compiled({name: 'Kai'});

输出: "hello: Kai"

FrankKai commented 5 years ago

handlebars.js

FrankKai commented 5 years ago

nunjucks

var nunjucks = require("nunjucks")
nunjucks.renderString('Hello {{ username }}', { username: 'James' });

输出: "Hello James"