我正在尝试使用带有 express-handlebars 作为 View 引擎的 Express 框架创建一个 nodejs 应用程序,但在尝试查看主页时遇到以下错误:
错误:您必须将字符串或 Handlebars AST 传递给 Handlebars.compile。你传递了 [object Object]
谁能告诉我这里出了什么问题。
链接到 github 存储库:https://github.com/bdinesh/LearningNode.git
下面是我要运行的代码:
index.js
var express = require('express'),
app = express(),
hbs = require('express-handlebars'),
// Create `ExpressHandlebars` instance with a default layout.
hbsInstance = hbs.create({
defaultLayout: 'main', extname: '.hbs'
}),
fortune = require('./lib/fortune.js'),
weatherData = require('./lib/weather.js');
app.engine('hbs', hbsInstance.engine);
app.set('view engine', 'hbs');
app.set('port', process.env.PORT || 3000);
app.use(express.static(__dirname + '/public'));
app.use(function(req, res, next) {
if (!res.locals.partials) {
res.locals.partials = {};
}
res.locals.partials.weather = weatherData.getWeatherData();
next();
});
app.get('/', function(req, res) {
res.render('home');
});
app.listen(app.get('port'), function() {
console.log('Express started on http://localhost:' + app.get('port'));
});
weather.js这个放在lib文件夹里
exports.getWeatherData = function getWeatherData() {
return {
locations: [
{
name: 'Portland',
forecastUrl: 'http://www.wunderground.com/US/OR/Portland.html',
iconUrl: 'http://icons-ak.wxug.com/i/c/k/cloudy.gif',
weather: 'Overcast',
temp: '54.1 F (12.3 C)',
},
{
name: 'Bend',
forecastUrl: 'http://www.wunderground.com/US/OR/Bend.html',
iconUrl: 'http://icons-ak.wxug.com/i/c/k/partlycloudy.gif',
weather: 'Partly Cloudy',
temp: '55.0 F (12.8 C)',
},
{
name: 'Manzanita',
forecastUrl: 'http://www.wunderground.com/US/OR/Manzanita.html',
iconUrl: 'http://icons-ak.wxug.com/i/c/k/rain.gif',
weather: 'Light Rain',
temp: '55.0 F (12.8 C)',
},
],
};
};
weather.hbs(局部 View )它位于 views/partials 文件夹中。
<div class="weatherWidget">
{{#each partials.weather.locations}}
<div class="location">
<h3>{{name}}</h3>
<a href="{{forecastUrl}}">
<img src="{{iconUrl}}" alt="{{weather}}">
{{weather}}, {{temp}}
</a>
</div>
{{/each}}
<small>Source: <a href="http://www.wunderground.com">Weather Underground</a></small>
</div>
home.hbs放在views文件夹中
<h1>Welcome to Meadowlark travel</h1>
{{> weather}}
最佳答案
请按如下方式更改您的代码:
<div class="weatherWidget">
{{#each partials.weatherData.locations}}
<div class="location">
<h3>{{name}}</h3>
<a href="{{forecastUrl}}">
<img src="{{iconUrl}}" alt="{{weather}}">
{{weather}}, {{temp}}
</a>
</div>
{{/each}}
<small>Source: <a href="http://www.wunderground.com">Weather Underground</a></small>
不幸的是,令人惊叹的 Web Development with Node and Express 中有一些过时的部分和错误。
勘误请引用此处:http://www.oreilly.com/catalog/errata.csp?isbn=0636920032977 这里是你遇到的问题:https://github.com/EthanRBrown/web-development-with-node-and-express/issues/28
关于javascript - 使用 Express-Handlebars View 引擎在 Express 4.x 框架中呈现局部 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36601801/