nodejs 返回html頁面--使用 ejs 模板

來源:互聯網
上載者:User

標籤:express   使用   home   test   --   擷取   設定   全域變數   bsp   

nodejs 可以直接在返回中使用html標籤,例如下面的格式,返回 hello world 將會使用 h1 字型。

app.get(‘/html‘,function(req,res){
  res.status(200).send(‘<h1>hello world</h1>‘);
});

 

"E" is for "effective." EJS is a simple templating language that lets you generate HTML markup with plain JavaScript. 

安裝ejs: npm install ejs 

例子一:

test_163:/home/exenode/jike # more ejslearn.js 
var express = require(‘express‘);

var app = express();

app.set(‘view engine‘,‘ejs‘);
app.set(‘views‘, __dirname + ‘/views‘);       //設定模板檔案檔案夾,__dirname為全域變數,表示網站根目錄。把view目錄下的檔案設定成模板檔案。

app.get(‘/‘,function(req,res){
  res.render(‘home.ejs‘,{name:‘zzz‘});    //向頁面模板傳遞參數,可以傳遞字串和對象。 並且把頁面模板返回給用戶端。以json的格式傳給 模板頁面。

});

app.listen(3002);
test_163:/home/exenode/jike # more views/home.ejs 
<html>
  <head>
    <title> new template </title>
  </head>
  <body>
    <p>Hello jikexueyuan</p>
    <p>Hi <%= name %></p>
  </body>
</html>

輸出的html頁面顯示:

Hello jikexueyuan

Hi zzz

 

例子二:

test_163:/home/exenode/jike # more ejslearn.js 
var express = require(‘express‘);
var app = express();

app.set(‘view engine‘,‘ejs‘);
app.set(‘views‘, __dirname + ‘/views‘);

app.get(‘/‘,function(req,res){
  res.render(‘home.ejs‘,{name:‘zzz‘});
});

app.get(‘/request/:name‘,function(req,res){                                         //佈建要求url中 request 後的字串,儲存到 name 這個變數中。
  // var locals = {name:‘westbrook‘,‘name‘:req.params[‘name‘]};       
  var locals = {name:req.params[‘name‘]}                                       // 把 req.params[‘name‘] 的值作為 字典locals 的 key name 的值。 
  res.render(‘home.ejs‘,locals);
});

app.listen(3002);
test_163:/home/exenode/jike # 
test_163:/home/exenode/jike # more views/home.ejs 
<html>
  <head>
    <title> new template </title>
  </head>
  <body>
    <p>Hello jikexueyuan</p>
    <p>Hi <%= name %></p>                             //擷取name的值。
    <p>name:<%= name %></p>                        //擷取name的值。

   </body>
</html>

結果:

在前台瀏覽器中訪問: http://192.168.1.163:3002/request/test123  ,頁面顯示:

Hello jikexueyuan

Hi test123

my name is:test123

 分類: 前端

nodejs 返回html頁面--使用 ejs 模板

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.