0

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.

Drown
  • 5,852
  • 1
  • 30
  • 49

2 Answers2

1

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"}));
});
DevAlien
  • 2,456
  • 15
  • 17
  • Awesome, I'm already familiar with Twig so Swig shouldn't be too hard to get used to. I just tried your code and it works just fine, I chose handlebars because it's the first one I saw, but I'll definitely look into Swig and will probably switch to it, considering how easy it is to use! Thanks ! – Drown Sep 13 '15 at 14:57
  • Cool, yes, i was used to Twig as well and so Swig just made my life easier. If it is the right answer, remember to mark it as the correct one, so other people can benefit from it. – DevAlien Sep 13 '15 at 15:00
1

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
});
7zark7
  • 10,015
  • 5
  • 39
  • 54