Nodejs 关于koa上用ejs但是最终的文件是.html

Nodejs 关于koa上用ejs但是最终的文件是.html

我只知道express 的做法: app.engine(’.html’, ejs.__express); app.set(‘view engine’, ‘html’); //替换文件扩展名ejs为html

但是我不晓得koa的要如何呢?求大神解答

3 回复

当然可以!下面是针对你所描述的问题的详细解答:

Node.js 中在 Koa 上使用 EJS 并将文件扩展名设置为 .html

在 Express 框架中,你可以通过配置来将 EJS 渲染的文件扩展名从默认的 .ejs 更改为 .html。但是在 Koa 框架中,默认情况下并没有提供这样的配置方法。不过,你可以通过中间件来实现这一点。

步骤

  1. 安装必要的依赖:
    • 安装 koakoa-ejs 中间件。
    • 你还需要安装 koa-send 来处理静态文件服务。
npm install koa koa-ejs koa-send
  1. 创建 Koa 应用并配置 EJS:
const Koa = require('koa');
const path = require('path');
const send = require('koa-send');
const ejs = require('koa-ejs');

const app = new Koa();

// 配置 Koa-EJS
ejs(app, {
    root: path.join(__dirname, 'views'),  // 设置模板文件夹路径
    layout: false,
    viewExt: 'html',  // 将视图文件扩展名设置为 .html
    cache: false,
    debug: true
});

// 定义一个简单的路由来渲染 EJS 模板
app.use(async ctx => {
    if (ctx.path === '/') {
        await ctx.render('index', { title: 'Hello Koa' });
    } else {
        await send(ctx, ctx.path.slice(1), { root: path.join(__dirname, 'public') });
    }
});

// 启动应用
app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});
  1. 创建 EJS 文件:

在你的项目目录中创建一个名为 views 的文件夹,并在其中创建一个名为 index.html 的文件(注意文件扩展名为 .html):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><%= title %></title>
</head>
<body>
    <h1>Hello <%= title %></h1>
</body>
</html>
  1. 启动服务器:

运行你的 Koa 应用,访问 http://localhost:3000,你应该能看到渲染出来的 HTML 页面。

总结

以上就是如何在 Koa 框架中使用 EJS 并将其文件扩展名设置为 .html 的步骤。通过配置 koa-ejs 中间件,你可以轻松地将 EJS 视图文件扩展名更改为 .html,并且在路由中渲染这些视图文件。这样你就可以像在 Express 中一样使用 .html 扩展名了。


我找到了: var render = views(__dirname + ‘/…/views’, { map: { html: ‘ejs’ } }); 原来这样就够了 太牛了

在 Koa 中使用 EJS 并将文件扩展名设置为 .html 可以通过配置中间件来实现。你可以使用 koa-ejs 这个中间件来实现这一点。

以下是一个简单的示例代码:

  1. 首先安装必要的依赖包:

    npm install koa koa-router koa-ejs
    
  2. 创建一个简单的 Koa 应用,并配置 EJS 模板引擎:

const Koa = require('koa');
const Router = require('koa-router');
const koaEjs = require('koa-ejs');

const app = new Koa();
const router = new Router();

// 配置koa-ejs
koaEjs(app, {
    root: __dirname + '/views',  // 设置模板文件夹路径
    layout: 'layout',            // 设置默认布局文件
    viewExt: 'html',             // 设置模板文件扩展名
    cache: false,                // 开发模式下可以关闭缓存
    debug: true                  // 开启调试模式
});

router.get('/', async ctx => {
    await ctx.render('index', { title: 'Hello World' });
});

app.use(router.routes()).use(router.allowedMethods());

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

在这个示例中,我们做了以下几件事:

  1. 引入并创建 Koa 和 Koa-Router 实例。
  2. 使用 koa-ejs 配置 EJS 模板引擎。设置模板文件夹路径、默认布局文件、模板文件扩展名为 .html,并根据需要开启缓存和调试模式。
  3. 定义路由 /,并在该路由中渲染 index.html 模板。
  4. 启动 Koa 服务器。

这样,你就可以在 Koa 应用中使用 EJS 模板引擎,并将文件扩展名设置为 .html

回到顶部