Using HTML in Express instead of Jade
Asked Answered
P

13

108

How to I get rid of Jade while using Express with Node.JS? I want to just use plain html. In other articles I have seen that people recommended app.register() which is now deprecated in the latest version.

Prochora answered 15/7, 2012 at 21:2 Comment(0)
P
82

You can do it this way:

  1. Install ejs:

    npm install ejs
    
  2. Set your template engine in app.js as ejs

    // app.js
    app.engine('html', require('ejs').renderFile);
    app.set('view engine', 'html');
    
  3. Now in your route file you can assign template variables

    // ./routes/index.js
    exports.index = function(req, res){
    res.render('index', { title: 'ejs' });};
    
  4. Then you can create your html view in /views directory.

Paedogenesis answered 1/3, 2014 at 15:11 Comment(3)
I have just started using node.js. The solution is not clear to me. I have a small html website. I need node.js for the sending emails through my site using nodemailer. I have installed everything required. However, have to idea what should go in the app.js file to make my website run using expressLiliuokalani
How to print the variable title in html file ?Thaddeusthaddus
If anyone is still wondering how to print the variable, like @MasterYoda asked, you can print it like this on the html: <%= title %>Wooster
F
63

Jade also accepts html input.
Just add a dot to the end of line to start submitting pure html.
If that does the trick for you then try:

doctype html              
html. // THAT DOT
    <body>     
        <div>Hello, yes this is dog</div>
    </body>

PS - No need to close HTML - that's done automagically by Jade.

Froma answered 14/10, 2013 at 19:43 Comment(2)
Doctype 5 is now deprecated. Use " doctype html " as the first line.Alicaalicante
Docs for the dot: pugjs.org/language/plain-text.html#block-in-a-tagGeorg
S
19

As of express 3 you can simply use response.sendFile

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});)

From the official express api reference:

res.sendfile(path, [options], [fn]])

Transfer the file at the given path.

Automatically defaults the Content-Type response header field based on the filename's extension. The callback fn(err) is invoked when the transfer is complete or when an error occurs.

Warning

res.sendFile provides client-side cache through http cache headers but it does not cache file contents on server-side. The code above will hit the disk on each request.

Solita answered 14/12, 2013 at 5:35 Comment(2)
I believe the OP still wants to use some kind of templating, just with regular HTML syntax. sendfile does not allow you to do any templating since it just sends bytes from a file. Further, I would recommend against using sendfile like this because it means you'll be hitting the disk every time a request comes in -- a huge bottleneck. For high-traffic pages, you should really do in-memory caching.Tamelatameless
@Tamelatameless if your're right about the OP intention, the question should be improved. You're right about hitting the disk on each request, i'll improve my answer to warn about this fact. Please consider improving yours to warn about the following: if you implement a customized engine you must implement too the catching feature (if desired), it's not handled by express.Solita
B
16

In my opinion, using something as big as ejs just to read html files is a bit heavy-handed. I just wrote my own template engine for html files that's remarkably simple. The file looks like this:

var fs = require('fs');
module.exports = function(path, options, fn){
    var cacheLocation = path + ':html';
    if(typeof module.exports.cache[cacheLocation] === "string"){
        return fn(null, module.exports.cache[cacheLocation]);
    }
    fs.readFile(path, 'utf8', function(err, data){
        if(err) { return fn(err); }
        return fn(null, module.exports.cache[cacheLocation] = data);
    });
}
module.exports.cache = {};

I called mine htmlEngine, and the way you use it is simply by saying:

app.engine('html', require('./htmlEngine'));
app.set('view engine', 'html');
Bennettbenni answered 23/5, 2014 at 16:27 Comment(0)
T
10

app.register() hasn't been depreciated, it has just been renamed to app.engine() since Express 3 changes the way template engines are handled.

Express 2.x template engine compatibility required the following module export:

exports.compile = function(templateString, options) {
    return a Function;
};

Express 3.x template engines should export the following:

exports.__express = function(filename, options, callback) {
  callback(err, string);
};

If a template engine does not expose this method, you're not out of luck, the app.engine() method allows you to map any function to an extension. Suppose you had a markdown library and wanted to render .md files, but this library did not support Express, your app.engine() call may look something like this:

var markdown = require('some-markdown-library');
var fs = require('fs');

app.engine('md', function(path, options, fn){
  fs.readFile(path, 'utf8', function(err, str){
    if (err) return fn(err);
    str = markdown.parse(str).toString();
    fn(null, str);
  });
});

If you're looking for a templating engine that lets you use 'plain' HTML, I recommend doT because it is extremely fast.

Of course, keep in mind that the Express 3 view model leaves view caching up to you (or your templating engine). In a production environment, you probably want to cache your views in memory so that you aren't doing disk I/O on every request.

Tamelatameless answered 15/7, 2012 at 21:56 Comment(2)
Please take a look at my answer, yours perfectly explains how to register template engines but there is a much easier way to transfer plain html files.Solita
@Tamelatameless : Your "extremely fast" hyperlink works in Firefox 41, but fails to run tests in Chromium Version 45.0.2454.101 Ubuntu 14.04 (64-bit). I wonder why.Alienation
U
4

You can use EJS with express which templates are HTML but support variables. Here is a good tutorial in how to use EJS in express.

http://robdodson.me/blog/2012/05/31/how-to-use-ejs-in-express/

Universality answered 30/3, 2013 at 16:41 Comment(0)
D
4

To make the render engine accept html instead of jade you can follow the following steps;

  1. Install consolidate and swig to your directory.

     npm install consolidate
     npm install swig
    
  2. add following lines to your app.js file

    var cons = require('consolidate');
    
    // view engine setup
    app.engine('html', cons.swig)
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', ‘html');
    
  3. add your view templates as .html inside “views” folder. Restart you node server and start the app in the browser.

Though this will render html without any issue, I would recommend you to use JADE by learning it. Jade is an amazing template engine and learning this will help you achieve better design & scalability.

Damascene answered 14/2, 2016 at 20:20 Comment(1)
The only really big problem with Jade is the indentation. If you get it wrong, code won't compile. Also, i wonder why Jade other than the fact that the only thing it does is shrink code...Behling
F
4

Well, it sounds like you want to serve static files. And there is a page for that http://expressjs.com/en/starter/static-files.html

Bizarre that nobody is linking to the documentation.

Facelift answered 11/10, 2016 at 18:45 Comment(1)
"Bizarre that nobody is linking to the documentation" I agree it's a trivial matter to use a different view language in Express.Joyajoyan
R
4

first check the compatibility version of template engine by using below line

express -h

then you have to use no view from the list.select no view

express --no-view myapp

now you can use your all html,css,js and images in public folder.

Ramirez answered 18/11, 2018 at 2:20 Comment(0)
I
1

Considering you have your routes already defined or do know how to do it.

app.get('*', function(req, res){
    res.sendfile('path/to/your/html/file.html');
});

NOTE: this route has to be placed after all the others since * accepts everything.

Instrumentalism answered 26/12, 2015 at 1:6 Comment(0)
B
1

since Jade supports HTML, if you just want to have .html ext, you can do this

// app.js
app.engine('html', require('jade').renderFile);
app.set('view engine', 'html');

then you just change file in views from jade to html.

Boxberry answered 3/2, 2016 at 19:37 Comment(1)
Don't you have to put a 'dot' or period before html markup?Hallerson
N
1

You can also directly include your html file into your jade file

include ../../public/index.html

Original answer: Express Generator Without Jade

Nador answered 7/6, 2017 at 12:37 Comment(0)
C
-10

If you want to use plain html in nodeJS, without using jade.. or whatever:

var html = '<div>'
    + 'hello'
  + '</div>';

Personnaly i'm doing fine with that.

The advantage is simplicity when control. You can use some tricks, like '<p>' + (name || '') + '</p>', ternary .. etc

If you want an indented code in the browser, you can do:

+ 'ok \
  my friend \
  sldkfjlsdkjf';

and use \t or \n at will. But i prefer without, plus it is faster.

Cirenaica answered 15/7, 2012 at 21:25 Comment(2)
I'd like to be able to use HTML files in Express (vs plain Node.JS)Prochora
ooooohh sorry (i'm french :p), so you can use the fs module. fs.readFile(htmlfile, 'utf8', function (err, file) {Cirenaica

© 2022 - 2024 — McMap. All rights reserved.