【问题标题】:Can only http module render ejs to html and pug to html?只能 http 模块将 ejs 渲染为 html 并将 pug 渲染为 html 吗?
【发布时间】:2019-01-19 17:34:41
【问题描述】:

如果是 http 模块,它有编码 utf8 的选项,但我认为 express 模块中没有选项,是真的吗?现在有办法通过 express 渲染吗?

const express = require('express');
const ejs = require('ejs');
const fs = require('fs');

const app = express();

app.use('/','utf8',(request,response) =>{
    fs.readFile('./render.ejs',(err,data)=>{
       fs.send(data) 
    });
});

app.listen(2000, ()=>{
    console.log('http://127.0.0.1:2000');
})

这段代码只是为了出错

【问题讨论】:

  • 我不清楚你想做什么?请问怎么用express.js渲染pug、ejs文件?
  • 确定这是我想知道的
  • 检查我的答案。

标签: node.js express pug render ejs


【解决方案1】:

概述

Pug、ejs - 这些是模板引擎的示例,您的问题的答案是:是的,express 支持它。更重要的是您甚至可以创建自己的模板引擎并在应用程序中使用它可以带来很多乐趣(官方文档教程:Developing template engines)。

要使用例如pug,您必须安装它:

  • npm install pug --save 或 yarn add pug

告诉 express 你将使用那个特定的:

  • app.set('view engine', 'pug')

示例

假设您已经安装了 pug、express 并且您的应用中有该模板:

html
  head
    title= title
  body
    h1= message

所以要使用自定义标题和消息来呈现它,就像这样:

app.get('/hello-world', function (req, res) {
  res.render('index', { title: 'Hey', message: 'Hello there!' })
})

当有人通过 GET 请求请求 '/hello-world' 路径时,它将提供 html 模板:

  • <title></title> 在头元素容器中 -> Hey
  • <h1></h1> 在正文元素中 -> Hello there!。

这里是完整的例子:Doc example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-26
    • 2017-01-29
    • 2011-06-01
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    • 2012-05-30
    • 2018-02-16
    相关资源
    最近更新 更多