Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to: Use ejs without express

Tags:

node.js

ejs

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!

like image 349
Manatax Avatar asked Apr 07 '14 00:04

Manatax


People also ask

Can you use EJS with HTML?

EJS is a simple templating language that lets you generate HTML markup with plain JavaScript.

How do I run an EJS file in my browser?

If you cannot open your EJS file correctly, try to right-click or long-press the file. Then click "Open with" and choose an application. You can also display a EJS file directly in the browser: Just drag the file onto this browser window and drop it.

Is EJS part of Express?

Template Engines and EJS:Template engine is a part of Express that enables us to use static files in our applications. Template engine converts variables to values and changes the template to HTML files to send to the client. The default template engine of Express is Jade, but EJS is the most commonly used engine.


1 Answers

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);
like image 53
Jaime Crespí Valero Avatar answered Sep 18 '22 08:09

Jaime Crespí Valero