Load templates from existing file

余生颓废 提交于 2019-12-25 12:45:41

问题


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.


回答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
});



回答2:


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"}));
});


来源:https://stackoverflow.com/questions/32550748/load-templates-from-existing-file

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