Search code examples
javascripthandlebars.jshapi.js

Display json data from helper module in hapijs using handlebars


I have a small hapijs app and want to display quotes in json format from a helper module but I can't display it.

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

If I return quotes[id] I get 'Word of the day by [object Object]' in the browser. If I change the handlebar html to {{{ quotes.author }}} it is empty. Is there something in hapijs that require tweaks to handlebars?

I tried to do a {{#each quotes}} ... {{/each}} but it does not loop. If I return JSON.stringify(quotes[id]); I get Word of the day by {"author":"Kobayashi Issa","text":"What a strange thing! to be alive beneath cherry blossoms."}

I'm aware quotes is called twice.

regards Claus


Solution

  • I changed the logic so I query postgresql and then pass the data on to the view making use of the nice npm promise library pg-bluebird, which for my part makes it easier to read.

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

    The use of a promise library in my view not only handy but takes out alot of confusion with callbacks I myself still feel I don't master that well.