Using interpolation within Node.js EJS includes

后端 未结 4 1013
天涯浪人
天涯浪人 2021-02-07 09:46

My Express app is using EJS, and my views directory looks like this:

./views
  ./contents
    home.ejs
  ./includes
    header.ejs
    footer.ejs
  layout.ejs
         


        
4条回答
  •  离开以前
    2021-02-07 10:45

    in your render function you can include fs.readFileSync and __dirname.

    Render your page with options like this

    res.render('pages/'+req.file,{file_get_contents:fs.readFileSync,__dirname:__dirname});
    

    Then you can use it in your .ejs page like this. This remains in server side.

    <% var products=JSON.parse(file_get_contents(__dirname+'/web/data/products.json','utf8')) %>
    

    You can print the data on client HTML like this.

    <%- JSON.stringify(products)%>
    

    Note : Using this method means you have fs included somewhere at the top of your script.

    var fs = require('fs')
    

提交回复
热议问题