繁体   English   中英

在ejs模板中使用嵌入式js加载静态文本文件

[英]Use embedded js in ejs template to load static text file

我目前正在使用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中要求模块。 您也可以尝试将文件加载到快速零件中。

 //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嵌入为脚本并在文档完成后加载它,但是我想这种方法应该更有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM