Nodejs EJS寻找template报错

Nodejs EJS寻找template报错

正在练手中,没有使用任何框架,从EJS官网下载的最新的包。 非常简单,下面是js文件

require('./ejs');                                                               

var data = { title: 'hello' };
var html = new EJS({ url: '/template.ejs' }).render(data);

console.log(html);

下面是ejs文件

<h 1><%= title %></h 1>

在运行时会抱以下错误 Downloads/temp/ejs.js:71 throw( {type: ‘EJS’, message: 'There is no template at '+url} ); ^ 希望各位可以指点迷津!


3 回复

标题:Nodejs EJS寻找template报错

内容: 大家好,我正在学习Node.js,并尝试使用EJS模板引擎。我没有使用任何框架,直接从EJS官网下载了最新的包。我遇到了一个错误,希望能得到大家的帮助。

以下是js文件的内容:

require('ejs');

var data = { title: 'hello' };
var html = new EJS({ url: '/template.ejs' }).render(data);

console.log(html);

下面是ejs文件的内容(template.ejs):

<h1><%= title %></h1>

当我运行这段代码时,会遇到以下错误:

Downloads/temp/ejs.js:71
throw( {type: 'EJS', message: 'There is no template at '+url} );
^
Error: [EJS] There is no template at /template.ejs
    ...

解释与解决方案

错误提示表明EJS找不到指定路径下的模板文件。这通常是因为路径设置不正确或者模板文件未被正确加载。

解决方案:

  1. 检查文件路径: 确保模板文件的路径是正确的。如果你的js文件和ejs文件在同一目录下,你应该使用相对路径来引用模板文件。

    修改后的js文件:

    require('ejs');
    
    var data = { title: 'hello' };
    var html = new EJS({ filename: './template.ejs' }).render(data);
    
    console.log(html);
    
  2. 确保文件存在: 检查template.ejs文件是否存在于指定路径下。

  3. 使用绝对路径(可选): 如果你需要使用绝对路径,可以这样做:

    var path = require('path');
    var ejsPath = path.resolve(__dirname, 'template.ejs');
    
    var html = new EJS({ filename: ejsPath }).render(data);
    

通过以上步骤,应该能够解决EJS找不到模板文件的问题。如果问题仍然存在,请再次检查路径和其他配置。


有人知道为什么报错吗?

根据你的描述,错误是因为EJS无法找到指定路径的模板文件。在Node.js中使用EJS时,需要确保路径正确,并且模板文件能够被正确加载。

示例代码修正

首先,你需要确保你的目录结构是正确的,并且路径是相对于当前文件的。假设你的项目结构如下:

/project-root
  /views
    template.ejs
  index.js

修改后的index.js:

const EJS = require('ejs');

// 确保路径正确,相对于当前文件
var data = { title: 'hello' };
var html = new EJS({ filename: './views/template.ejs' }).render(data);

console.log(html);

解释

  1. 路径问题:在new EJS({ url: '/template.ejs' }) 中,/template.ejs 是一个绝对路径。对于 Node.js 来说,通常路径是相对于项目的根目录或当前文件的。使用 filename 选项来指定模板文件的路径,这样可以避免路径问题。

  2. 模板文件路径:确保你的模板文件(如 template.ejs)放置在一个合理的目录下,例如 views 目录。同时,路径应相对应当前文件或项目的根目录。

  3. 安装 EJS 包:确保你已经安装了 EJS 模块。如果还没有安装,可以通过 npm install ejs 安装。

通过以上修改,你应该可以解决找不到模板文件的问题。

回到顶部