Ejs-mate

  Ejs模板引擎不能使用layout语法,在整理html结构时相当不好用。但是Jackson Tian同学开发的ejs-mate为ejs添加了这个功能。那么,怎么在项目中使用ejs-mate呢?

安装esj-mate

  命令行进入项目的根目录,然后使用npm安装。

$ npm install ejs-mate --save

使用ejs-mate

  编写一个layout文件, boilerplate.ejs:

<!DOCTYPE html>
<html>
  <head>
    <title>It's <%= who %></title>
  </head>
  <body>
    <section>
      <%- body -%>
    </section>
  </body>
</html>

  编写一个模板,index.ejs,该模板使用layout.ejs作为layout:

<% layout('boilerplate') -%>
<h1>I am the <%= what %> template</h1>

  使用Express 4.0应用来生成渲染模板:

var express = require('express'),
  engine = require('ejs-mate'),
  app = express();

// use ejs-locals for all ejs templates:
app.engine('ejs', engine);

app.set('views',__dirname + '/views');
app.set('view engine', 'ejs'); // so you can render('index')

// render 'index' into 'boilerplate':
app.get('/',function(req,res,next){
  res.render('index', { what: 'best', who: 'me' });
});

app.listen(3000);

  最后结果

<!DOCTYPE html>
<html>
  <head>
    <title>title</title>
  </head>
  <body>
    <section>
      <h1>template</h1>
    </section>
  </body>
</html>

ejs-mate语法

layout(view)

  在模板中的任何位置调用此方法,会将此模板的内容套用在layout的<%- body -%>中。

partial(view, optionsOrCollection)

  当在模板中调用这个方法时,会将目标view的内容嵌套到当前的模板中,并表,可以通过optionsOrCollections将相关参数传递给目录view。

block('name')

  使用block('name')来创建一个块对象。这个块对象有4个方法,分别是append()prepend()replace()toString()

基本用法 body-template.ejs

<% layout('boilerplate') -%>
<% block('head').append('<link type="text/css" href="/foo.css">') %>
<h1>I am the template</h1>
<% block('footer').append('<script src="/bar.js"></script>') %>

layout文件,boilerplate.ejs:

<!DOCTYPE html>
<html>
  <head>
    <title>I'm the layout</title>
    <%- block('head').toString() %>
  </head>
  <body>
    <section>
      <%-body -%>
    </section>
    <%= block('footer').toString() %>
  </body>
</html>

最终结果

<!DOCTYPE html>
<html>
  <head>
    <title>I'm the layout</title>
    <link type="text/css" href="/foo.css">
  </head>
  <body>
    <section>
      <h1>I am the template</h1>
    </section>
    <script src="/bar.js"></script>
  </body>
</html>

Alan Yeh

简单技术控,喜欢接触各类技术

GZ, China http://yerl.cn