How to: Use ejs without express

别等时光非礼了梦想. 提交于 2019-12-04 18:57:53

问题


I'm starting with node in general, and I'm attempting to do a site without express. I would none the less want to use ejs to inject my html and this is where my problem is... How do I attach the ejs.render(...) to the response?

PS: I know it might be a better option to use express, but I want to know how it works underneath before bridging it.

Something like:

var ejs = require("ejs");

function index (response, request, sequelize) {
    response.writeHead(200, {"Content-Type": "text/html"});
    test_data = "test data";
    response.end(ejs.render("./views/home.html",test_data));
}

exports.index = index;

But that works ^_^

Thanks!


回答1:


First of all, You need install ejs -> $ npm install ejs --save

Simple example:

main.ejs:

<p> <%= exampleRenderEjs  %> </p>

server.ejs

var ejs = require('ejs');
var fs = require('fs');

var htmlContent = fs.readFileSync(__dirname + '/main.ejs', 'utf8');

var htmlRenderized = ejs.render(htmlContent, {filename: 'main.ejs', exampleRenderEjs: 'Hello World!'});

console.log(htmlRenderized);



回答2:


There is a project called Consolidate.js which provides a common API for many template engines. This ensures they can all be interchangeable. If you want to render templates directly, you want to be compatible with this API.

Sample code from the Consolidate.js README:

var cons = require('consolidate');
cons.swig('views/page.html', { user: 'tobi' }, function(err, html){
  if (err) throw err;
  console.log(html); // Or write to your `res` object here
});

This sample is for Swig, but similar code works for EJS or any of the compatible engines.




回答3:


Example from some book: template.ejs

<html>
  <head>
    <style type="text/css">
      .entry_title { font-weight: bold; }
      .entry_date { font-style: italic; }
      .entry_body { margin-bottom: 1em; }
    </style>
  </head>
  <body>
    <% entries.map(entry => { %>
      <div class="entry_title"><%= entry.title %></div>
      <div class="entry_date"><%= entry.date %></div>
      <div class="entry_body"><%= entry.body %></div>
    <% }); %>
  </body>
</html>


function blogPage(entries) {
    const values = { entries };
    const template = fs.readFileSync('./template.ejs', 'utf8');
    return ejs.render(template, values);
}


const server = http.createServer((req, res) => {
    const entries = getEntries();
    const output = blogPage(entries);
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(output);
    console.log('run server');
});
server.listen(8000);


来源:https://stackoverflow.com/questions/22901787/how-to-use-ejs-without-express

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!