express 中使用ejs

这篇博客介绍了如何在Express应用中使用EJS模板引擎。文件组织包括将动态模板放在.views目录,静态资源放于.public目录,布局文件置于.layouts目录。EJS的基本语法、可用的对象如.scripts和.stylesheets,以及具体的使用示例也被详细阐述。

express中使用ejs

var express = require('express');//需要安装 express :  cnpm i --save express
var app = express();

app.set("view engine","ejs");//模版引擎设置为 ejs

文件组织

在express中使用ejs,文件组织遵循express。
.views——-放置动态模版
.public——放置静态网页
.layouts—–放置布局文件

基本语法

.<% code %>//    无缓冲的条件语句元素
.<%= code %>//转义HTML,该code并且会打印出来
.<%- code %>//非转义的buffering,该code并且会打印出来
.<% include file %>//内嵌别的文件
.<% layout(file) -%>//指定布局文件
.<% script(file) -%>//包含js脚本文件
.<% stylesheet(file) -%>//包含css文件
.<% block(code, code) -%>//指定块内容    

基本对象

.scripts
包含的脚本

.stylesheets
包含的css

.blocks
包含的块

例子

//index.ejs
<% layout('boilerplate') -%>
<% script('foo.js') -%>
<% stylesheet('foo.css') -%>
<h1>I am the <%=what%> template</h1>
<% block('header', "<p>I'm in the header.</p>") -%>
<% block('footer', "<p>I'm in the footer.</p>") -%>
//boilerplate.ejs
<!DOCTYPE html>
<html>
  <head>
    <title>It's <%=who%></title>
    <%-scripts%>
    <%-stylesheets%>
  </head>
  <body>
    <header>
      <%-blocks.header%>
    </header>
    <section>
      <%-body -%>
    </section>
    <footer>
      <%-blocks.footer%>
    </footer>
  </body>
</html>
//app.js
var express = require('express')
  , engine = require('ejs-locals')
  , 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>It's me</title>
    <script src="foo.js"></script>
    <link rel="stylesheet" href="foo.css" />
  </head>
  <body>
    <header>
      <p>I'm in the header.</p>
    </header>
    <section>
      <h1>I am the best template</h1>
    </section>
    <footer>
      <p>I'm in the footer.</p>
    </footer>
  </body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值