javascript - Handlebars 模板呈现为原始 html

标签 javascript node.js express handlebars.js

我试图获得一个使用 Node 和 Handlebars 运行的简单页面,但该页面无法正确呈现。当我去 http://localhost:8080/我只是在浏览器中获取原始 HTML 文本。这是我的代码:

ma​​in.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>

ma​​in.handlebars

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

我在 NetBeans 中运行此操作,但即使我尝试通过命令行执行此操作,结果也是相同的。

编辑:更奇怪的是,它在 Firefox 中渲染得很好,但在 IE 或 Chrome 中则不然。

EDIT2:更奇怪。如果我将端口更改为其他端口,Firefox 将停止正确渲染。 Firefox 仅在端口 8080 时才能正确呈现。

EDIT3:这是我所看到的图像: enter image description here

EDIT4:我对 main.handlebars 进行了更改,保存了它,测试了它,撤消了更改并再次保存了它(因此它回到了原始状态),现在 Firefox 也不会渲染。

EDIT5:它现在似乎可以正常工作,但我完全不知道为什么。如果有人想仔细查看,我将文件保存在这里:https://github.com/tliss/ExerciseApp

最佳答案

快速 Handlebars 模板有同样的问题,试试这个

  • 三花括号而不是双花括号
  • 清除缓存
  • 删除 res.type()
  • 使用这两行来设置 View 引擎

app.engine('handlebars', exphbs({defaultLayout: 'main'})); app.set(' View 引擎', ' Handlebars ');

关于javascript - Handlebars 模板呈现为原始 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42751686/

相关文章:

javascript - 有没有办法让我的 Spring 后端告诉我的 ReactJS 客户端应用程序它将渲染其项目中的哪个组件

javascript - Mongoose 用 promise 保存并填充

javascript - 使用 application/x-www-form-urlencoded 使用 node.js 在发布请求中发送数组

javascript - D3js "bars.enter().attr"不是一个函数

javascript - 如何在 JavaScript 中获取外部元素值

javascript - 如何删除 summernote 工具提示 v.0.8.2

node.js - 关于 NodeJS 中的嵌套 Promise

javascript - Node.js 迭代器接口(interface)

javascript - 如何在 Node.js 中将 base64 解码为图像文件?

node.js - Gulp-connect 显示错误 'listen EADDRINUSE' 8080