【问题标题】:Display json data from helper module in hapijs using handlebars使用把手在 hapijs 中显示来自辅助模块的 json 数据
【发布时间】:2015-03-29 20:23:53
【问题描述】:

我有一个小型 hapijs 应用程序,想从辅助模块中显示 json 格式的引号,但我无法显示它。

index.js:

server.views({
  engines: {
    html: require('handlebars')
  },
  context: defaultContext,
  relativeTo: __dirname,
  path: './views',
  layoutPath: './views/layout',
  helpersPath: './views/helpers',
  partialsPath: './views/partials',
  layout: false,
  isCached: false
});

server.route({
  method: 'GET',
  path: '/quotes',
  handler: function (request, reply) {
    reply.view('quotes');
  }
});

quotes.html:

<h1>Word of the day by {{{ quotes }}}</h1>
{{{quotes}}}

quotes.js:

module.exports = function () {
    var quotes = [
        { author: "Kobayashi Issa", text: "What a strange thing!<br>to be alive<br>beneath cherry blossoms." },
        { author: "Kobayashi Issa", text: "Summer night--<br>even the stars<br>are whispering to each other." },
        { author: "Kobayashi Issa", text: "Never forget:<br>we walk on hell,<br>gazing at flowers." },
        { author: "Kobayashi Issa", text: "Here<br>I'm here-<br>the snow falling." }
    ];
    var id = Math.floor(Math.random() * quotes.length);
    return quotes[id].text;
};

如果我返回引号[id],我会在浏览器中获得“[object Object] 的每日词汇”。如果我将车把 html 更改为 {{{ quotes.author }}} 它是空的。 hapijs 中是否有需要调整车把的东西?

我试图做一个 {{#each quotes}} ... {{/each}} 但它没有循环。如果我返回 JSON.stringify(quotes[id]);我得到了 {"author":"Kobayashi Issa","text":"多么奇怪的事情! 活着 樱花下。”}

我知道引号被调用了两次。

问候 克劳斯

【问题讨论】:

    标签: javascript handlebars.js hapijs


    【解决方案1】:

    我更改了逻辑,因此我查询 postgresql,然后使用漂亮的 npm promise 库 pg-bluebird 将数据传递到视图,这对我来说更容易阅读。

    index.js:

    server.route({
      method: 'GET',
      path: '/participants',
      handler: function (request, reply) {
        var res = [];
        pg.connect(db)
          .then(function (connection) {
            cnn = connection;
            return cnn.client.query('select * from participants');
          })
          .then(function (result) {
            cnn.done();
            reply.view('participants', { p: result.rows});
          })
          .catch(function (error) {
            console.log(error);
          });
      }
    });
    

    participants.html:

    {{#each p }}
        <li>{{this.id}}, {{this.data.name}}, {{this.data.gender}}</li>
    {{/each}}
    

    在我看来,promise 库的使用不仅方便,而且消除了很多与回调的混淆,我自己仍然觉得我没有掌握得很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-27
      • 1970-01-01
      • 2016-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-08
      相关资源
      最近更新 更多