简体   繁体   中英

Handlebars template being rendered as raw html

I'm trying to just get a simple page running with node and handlebars, but the page doesn't render correctly. When I go to http://localhost:8080/ I just get raw HTML text in the browser. Here's my code:

main.js

var express = require('express');
var app = express();

var handlebars = require('express-handlebars').create({defaultLayout:'main'});
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');

app.set('port', 8080);

app.get('/',function(req,res){
    res.type('text/plain');
    res.render('home');
});

app.listen(app.get('port'), function(){
    console.log('Express started on http://localhost:' + app.get('port') + '; press Ctrl-C to terminate.');
});

home.handlebars

<h1>The Home Page</h1>

main.handlebars

<!doctype html>
<html>
<head>
    <title>Demo Page</title>
</head>
<body>
    {{{body}}}
</body>
</html>

I'm running this in NetBeans but even if I try doing it through the command line, the result is the same.

EDIT: Even weirder, it renders fine in Firefox, but not in IE or Chrome.

EDIT2: More weirdness. If I change the port to something else, Firefox will stop rendering correctly. Firefox only renders correctly when its port 8080.

EDIT3: Here's an image of what I'm seeing: 在此处输入图片说明

EDIT4: I made a change to main.handlebars, saved it, tested it, undid the change and saved it again (so it was back to its original state), and now Firefox won't render either.

EDIT5: It seems to be working now and I have absolutely no idea why . If anyone wants to take a closer look, I have the files saved here: https://github.com/tliss/ExerciseApp

Had same problem with express handlebars template, try this

  • triple curly braces instead of double
  • clear cache
  • remove res.type()
  • use these two lines for setting view engine

app.engine('handlebars', exphbs({defaultLayout: 'main'})); app.set('view engine', 'handlebars');

Remove res.type('text/plain'); and restart the server and clear browser cache (on Chrome you can use ctrl + F5 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM