Drown
Drown

Reputation: 5982

Load templates from existing file

I'm using Handlebars in my NodeJS application as my templating engine.

I've put all my templates in a views folder like so :

-
  - /controllers
  - /views
    - index.html
  - server.js

Here's my code to render the template when the user access a given URL (using express for routing) :

app.get("/", function(req, res){

    var template = handlebars.compile("views/index.html");
    var data = {"name": "Charles"};
    var result = template(data);

    res.send(result);
});

I'm trying to render a template from a file, but it's not working. This is what the browser outputs directly when I'm accessing the / URL :

views/index.html

That makes sense, since it's interpreting the given param as a string directly and not as a path to an external template.

How can I load my template file (in this case the one in views/index.html to a variable, so that I can then render the template?

The only examples I found were storing all the templates in a file and loading them via AJAX, but all these examples were from "front-end" handlebars and not when using it with Node.

Is it possible to achieve what I want? I looked at the documentation but it's hard to find good infos for handlebars with NodeJS.

Upvotes: 0

Views: 2094

Answers (2)

7zark7
7zark7

Reputation: 10145

From your description, it sounds like you want handlebars as view engine, with dynamic views. You don't need to do this manually, here is an example (using express-handlebars):

var handlebars = require('express-handlebars');

app.engine('.html', handlebars({layout: false, extname: '.html'}));
app.set('view engine', '.html');

app.get("/:view", function(req, res){
  var view = req.params.view;
  res.render(view, { "name": "Charles" });  // Whatever data you want
});

Upvotes: 1

DevAlien
DevAlien

Reputation: 2476

With handlebars you have to load the file yourself or you can precompile the files (using grunt/gulp maybe) I feel way more confortable with swig ( http://paularmstrong.github.io/swig/ ) It is very simple to use. And it has also integration with express if you want.

var swig  = require('swig');
swig.renderFile('/path/to/template.html', {
    pagename: 'awesome people',
    authors: ['Paul', 'Jim', 'Jane']
});

In your case

app.get("/", function(req, res){
    res.send(swig.renderFile('views/index.html', {"name": "Charles"}));
});

Upvotes: 1

Related Questions