【问题标题】:Hapi handlebar template not displaying json object dataHapi 车把模板不显示 json 对象数据
【发布时间】:2015-11-18 16:10:11
【问题描述】:

大家好,我有一个简单的处理程序,它可以读取 mysql 表并将 json obj 返回到路由,就像这样。

处理程序

var PostStore = {};

PostStore.getAllPosts = function(){
    conn.query('SELECT * FROM posts',function(err, result){
        if(err){
            console.log(err);
        }
        console.log(JSON.parse(JSON.stringify(result)));
        return JSON.parse(JSON.stringify(result));
    });
}


module.exports = PostStore;

路由器

{
    path: '/',
    method: 'GET',
    handler: function (request, reply) {
        console.log(PostStore.getAllPosts);
        reply.view('index', { 
            title: 'My home page',
            posts: PostStore.getAllPosts
        });
    }
}

index.html

<h1>{{title}}</h1>

{{#each posts}}
<h1>{{this.title}}</h1>
{{/each}}

这是控制台输出的样子

[Function]
[ { id: 1,
    title: 'Hello World',
    body: 'My First Post on this cool Hapi Blog!',
    date: null } ]

如您所见,sql 结果被解析为 JSON obj,但未从把手读取。另请注意,{{title}} 按预期显示“我的主页”。

任何帮助将不胜感激!谢谢。

【问题讨论】:

    标签: node.js express handlebars.js hapijs


    【解决方案1】:

    PostStore.getAllPosts 是异步的,你需要在它的回调函数中渲染视图。

    PostStore.getAllPosts(function (err, posts) {
    // render the view 
    });
    

    【讨论】:

    • 我将如何调用 PostStore.getAllPosts 并将“title”传递给索引视图?
    【解决方案2】:

    在视图中呈现异步方法的唯一方法是在预处理程序中调用此方法并分配返回值,以便您可以在视图中呈现返回的数据。更多解释请参见 hapi 的文档http://hapijs.com/api#route-prerequisites

    在 PostStore 例程中此代码

    PostStore.getAllPosts = function(callback){
        conn.query('SELECT * FROM posts',function(err, result){
            if(err){
                return callback(err);
            }
    
            return callback(result);
    });
    

    }

    然后在处理程序代码中

    const getPosts = function (request, reply) {
    
        ... // do something async to set posts
        PostStore.getAllPosts(function(err, results) {
    
            if (err) {
                return reply('Error occurred')
            }
            reply(results);
        };
    };
    
    server.route({
        method: 'GET',
        path: '/',
        config: {
            pre: [
                { method: getPosts, assign: 'posts' }
        ],
            handler: function (request, reply) {
    
                reply.view('index', { 
                    title: 'My home page',
                    posts: request.pre.posts,
                });
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2015-05-18
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-13
      相关资源
      最近更新 更多