javascript - 在ejs模板中使用嵌入式js加载静态文本文件
问题描述
我目前正在使用 ejs 视图模板开发 nodejs 应用程序。我正在尝试通过模板中的嵌入式 js 调用存储在文本文件中的大量文本。这是当前模板的代码
<!DOCTYPE html>
<html>
<head>
<link href="/assets/styles/index.css", rel="stylesheet", type="text/css">
</head>
<body>
<% var name = 'A Tale of Two Star Crossed Idiots: Act ' + act%>
<%include partial/header.ejs%>
<p>
//the following line is completely wrong
<%= require('fs').readFileSync('.'+__dirname + '/assets/text/romeo and juliet/act' + act + '.txt') %>
</p>
</body>
</html>
这是我运行它时发生的错误
require is not defined
at eval (eval at compile (D:\Web Projects\NodeJs Test\node_modules\ejs\lib\ejs.js:618:12), <anonymous>:30:7)
at returnedFn (D:\Web Projects\NodeJs Test\node_modules\ejs\lib\ejs.js:653:17)
at tryHandleCache (D:\Web Projects\NodeJs Test\node_modules\ejs\lib\ejs.js:251:36)
at View.exports.renderFile [as engine] (D:\Web Projects\NodeJs Test\node_modules\ejs\lib\ejs.js:482:10)
at View.render (D:\Web Projects\NodeJs Test\node_modules\express\lib\view.js:135:8)
at tryRender (D:\Web Projects\NodeJs Test\node_modules\express\lib\application.js:640:10)
at Function.render (D:\Web Projects\NodeJs Test\node_modules\express\lib\application.js:592:3)
at ServerResponse.render (D:\Web Projects\NodeJs Test\node_modules\express\lib\response.js:1008:7)
at D:\Web Projects\NodeJs Test\index.js:14:9
at Layer.handle [as handle_request] (D:\Web Projects\NodeJs Test\node_modules\express\lib\router\layer.js:95:5)
有谁知道如何正确地做到这一点?谢谢。
解决方案
不幸的是,在 ejs 中需要模块是不可能的。您也可以尝试在 express 部分中加载文件。
//Node.JS Backend
app.get("/foo",(req,res)=>{
const act = req.query.act; //Act as Query Parameter in URL
fs.readFile('.'+__dirname+'/assets/text/romeo and juliet/act'+act+'.txt',"utf8",(error,data)=>{
//Add your error handling (if(error))
res.render("file",{bar:data});
});
});
<!DOCTYPE html>
<html>
<head>
<link href="/assets/styles/index.css", rel="stylesheet", type="text/css">
</head>
<body>
<% var name = 'A Tale of Two Star Crossed Idiots: Act ' + act%>
<%include partial/header.ejs%>
<p>
//the following line is completely wrong
<%- bar %>
</p>
</body>
</html>
否则,您可以将 fs 作为脚本嵌入并在文档完成时加载它,但我猜这种方法应该更有效。
推荐阅读
- hbase - HBase 从 1.4 直接升级到 2.3
- python - 我需要生成以下输出
- eclipse - 为什么单个 `System.out.println(i);` 在 Eclipse 中给出两次输出?
- c# - 由于无法将类型 JsonElement 转换为类型 System.String 而导致的内部错误评估表达式
- delphi - TListbox TStyleobject 未释放
- android - 我无法理解为什么凌空无法在我的应用程序中获得 Json 获取请求的响应?
- javascript - 为什么 this.tail 在我的 Linkedlist 类中更改 this.head 的属性?
- bash - 如何从 txt 文件中查找字符串并将其存储在 BASH 中的变量中
- python - How to modify the syntax of data serie?
- powerbi - 基于 2 个条件的条件格式