【问题标题】:Is there a way to keep the file extension of ejs file as .html?有没有办法将ejs文件的文件扩展名保持为.html?
【发布时间】:2015-02-07 14:20:40
【问题描述】:

我正在使用 ejs 模板引擎开发 expressjs 应用程序。但我想使用保持 ejs 文件的扩展名,如 home.html 而不是使用 home.ejs。原因是我使用 Visual Studio 进行开发,而 Visual Studio 不支持 ejs 文件。所以代码提示格式和突出显示不起作用。

var express = require("express");
var app = express();


app.set("view engine", "ejs");//setting ejs view engine
app.set("views", "./views");

app.get("/", function (req, res) {
    res.render("home");
});

app.listen(3000, function () {
    console.log("Server is listening on port 3000");
})

【问题讨论】:

  • 你为什么要这样做而不是配置 Visual Studio 以便它知道 .ejs 文件应该被视为 .html?这似乎是在问错误的问题。
  • 我认为@loganfsmyth 是对的,您需要配置您的VS 以确认.ejs 文件,以便将该文件视为html。

标签: javascript node.js express ejs embedded-javascript


【解决方案1】:

我设法解决了这个问题,我的代码类似于@homam 的答案,但我会更完整地编写代码

const http = require('http');
const path = require('path');
const express = require('express');
const engine = require('ejs');
const app = express();

app.engine('html', engine.__express);
app.set('views', path.join(__dirname, './views'));
app.set('view engine', 'html');

//this route will open profil.html in folder ./views
app.get('/', (req, res) => {
  //render file profil.html
  res.render('profil', {
    name: 'Danang Ponorogo'
  });
});

var server = http.createServer(app);
server.listen(3001, () => {
  console.log('Server is running at port 3001');
});

希望对您有所帮助。谢谢。

【讨论】:

【解决方案2】:

你可以使用app.engine(ext, callback)

使用您的视图引擎和顶部附近的视图设置进行以下设置:

app.engine('html', require('ejs').renderFile);

那么当你调用res.render时,唯一的区别就是你需要指定扩展名:

app.get('/',function(req,res){
    res.render("home.html", { myString: "I'm a normal string!" });  
});

您会发现 <%=myString%> 的处理方式与您在 .ejs 文件中的预期一样。

【讨论】:

    【解决方案3】:

    我在使用 Visual Studio 处理 ejs 文件时遇到了类似的问题。我认为最好的方法是通过转到菜单 - TOOLS-->Options-->Text Editor-->FileExtension 并添加针对 HTML Editor 的 ejs 文件扩展名来配置 Visual Studio 以将 ejs 文件解释为 html。 Screenshot

    【讨论】:

      【解决方案4】:

      使用ejs npm模块的app.engine('.html', require('ejs').__express);

      app.engine('.html', require('ejs').__express);
      app.set('view engine', 'ejs');
      

      【讨论】:

      • 你知道我们是否可以对 js 文件做同样的事情,因为app.engine('.js', require('ejs').__express); 似乎不起作用? `
      • 当我在 index.html 文件中使用小型 ejs 时,它似乎对我不起作用:<% if (!user) { %> <p>hello</p> <% } %>
      猜你喜欢
      • 1970-01-01
      • 2017-08-21
      • 1970-01-01
      • 2020-02-24
      • 1970-01-01
      • 2023-03-14
      • 2019-05-20
      • 2018-10-19
      • 2012-10-07
      相关资源
      最近更新 更多