javascript - 使用 handlebars.js 显示 JSON 数据

标签 javascript json node.js express handlebars.js

我需要弄清楚如何将完整的 JSON 响应打印到我的页面(甚至部分页面)上,但我似乎无法弄清楚。稍后我将最终用更多上下文填充页面。

JS文件:

app.get('/', function(req, res) {
var context

apiLib.fetch('acct:chars', function(err, result){
    if(err) throw err

    context = result;
    console.log(result); 
    res.render('/', context);

    });

});

Handlebars :

 {{#each context.characters}}
 {{this.name}} 
 {{/each}}

JSON 数据:

{
  "result": {
    '1234':{               //this is the character ID
      "characters": {
        "name": 'Daniel',
        "CharacterID": '1234'
        etc...
    }
   }
 }

我的页面没有打印任何内容,但控制台记录了所有内容。我正在使用 express.js 来处理路由。

最佳答案

如果你想显示字符串化的JSON,你可以使用一个helper

JS

Handlebars.registerHelper('toJSON', function(obj) {
    return JSON.stringify(obj, null, 3);
});

HTML <pre>{{toJSON result}}</pre>

关于javascript - 使用 handlebars.js 显示 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34039555/

相关文章:

javascript - MVC Web Api 使用 Ajax 获取数据

java - 向 json 对象 java 中的数组添加新元素

javascript - 通过 Javascript 访问 JSON 数组

php - Composer 创建本地包

c# - 从 C# 控制台应用程序运行 npm init

javascript - PHP 变量未在 Javascript 中回显

php - 如何使用 Jquery 正确解析数据库中的结果数组?

javascript - 将 blob 转换为 arraybuffer,无需 filereader/xmlttprequest

javascript - 逐行读取文本文件并执行函数?

jquery - 为什么 onclick 函数不能在类上运行?