2016-12-26 45 views
0

我可以向你保證,我已經對我的顯示器大聲說了,現在花幾個小時來理解這一點。 首先,我無法理解具有不能執行簡單比較功能的句柄的模板引擎的概念。NodeJS/Express/ExpressHandlebars - 全球幫手功能

無論如何。我有這個輔助函數,在添加到單個路由時非常有用,正如您在此處所看到的。不過,我真的很想將它作爲全局函數添加到我創建的app.js文件中。我可以向你保證,幫助函數的GITHub示例不起作用。

任何幫助將真正被讚賞。

我的index.js文件。

/* GET home page. */ 
router.get('/', function(req, res, next) { 
Coupon.find(function(err, docs) 
{ 

    res.render('main/index', { 

    title: 'Coupon Site new for all', 
    coupons: docs, 

    //helpers 
    helpers: { 
     eq: function (v1, v2) { 
      return v1 === v2; 
     }, 
     ne: function (v1, v2) { 
      return v1 !== v2; 
     }, 
     lt: function (v1, v2) { 
      return v1 < v2; 
     }, 
     gt: function (v1, v2) { 
      return v1 > v2; 
     }, 
     lte: function (v1, v2) { 
      return v1 <= v2; 
     }, 
     gte: function (v1, v2) { 
      return v1 >= v2; 
     }, 
     and: function (v1, v2) { 
      return v1 && v2; 
     }, 
     or: function (v1, v2) { 
      return v1 || v2; 
     } 
     }, 
    }); 

    }); 

}); 

而在app.js顯然我應該可以做這樣的事情。文檔中沒有什麼,我想,我應該以某種方式從ExpressHandlebars documentation導入hbs變量在我index.js

var hbs = exphbs.create({ 
    // Specify helpers which are only registered on this instance. 
    helpers: { 
     foo: function() { return 'FOO!'; }, 
    bar: function() { return 'BAR!'; } 
    } 
}); 

回答

0

例子:

var express = require('express'); 
var exphbs = require('express-handlebars'); 

var app = express(); 

var hbs = exphbs.create({ 
    // Specify helpers which are only registered on this instance. 
    helpers: { 
     foo: function() { return 'FOO!'; }, 
     bar: function() { return 'BAR!'; } 
    } 
}); 

app.engine('handlebars', hbs.engine); 
app.set('view engine', 'handlebars'); 

app.get('/', function (req, res, next) { 
    res.render('home', { 
     showTitle: true, 

     // Override `foo` helper only for this rendering. 
     helpers: { 
      foo: function() { return 'foo.'; } 
     } 
    }); 
}); 

app.listen(3000); 

你必須做的那麼什麼給你的gt()lt()等全局範圍:在hbs(===將它們傳遞給exphbs.create())變量內聲明它們。

render()傳遞handlebars屬性,可以覆蓋hbs定義的助手。