node.js - 我如何让 D3 读取 Handlebars 上下文对象

标签 node.js express handlebars.js

我正在使用 Node + Express.js。我的路线之一渲染了 Handlebars 模板及其上下文。相关部分:

my_data = JSON.parse(body);
response.render( 'activity', my_data);

我的问题:在那activity.hbs内模板,如何使用 D3 从 my_data 创建绘图JSON 对象。在activity.hbs的相关部分我已经尝试过了

<script type="text/javascript">
      Handlebars.registerHelper('json', function(context) {
          return JSON.stringify(context);
      });

     var datas = {{json my_data}}
     d3.select("body")
     .datum(datas)
     .enter()
    #do stuff with data
  </script>

我在reading this question之后添加了助手。当我尝试渲染 View 时,出现错误:

Missing helper: 'json' at Object.<anonymous>

使用 Helper 是解决此问题的正确方法吗?如何让 D3 读取我的上下文对象?

最佳答案

我认为问题出在你的助手定义中,基本上你在错误的地方定义了助手。 定义一个helper,基于express3-handlebars的文档您必须在 Express 应用程序代码中注册它:

var express = require('express'),
    exphbs  = require('express3-handlebars'),

  app = express(),
  hbs;

  hbs = exphbs.create({
    // Specify helpers which are only registered on this instance.
    helpers: {
      // Your custom helper here
      json: function(context) { return JSON.stringify(context); }
    }
  });
  // Register it
  app.engine('handlebars', hbs.engine);
  app.set('view engine', 'handlebars');

关于node.js - 我如何让 D3 读取 Handlebars 上下文对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21666062/

相关文章:

node.js - Electron Builder 代码签名下载证书错误

node.js - 无法使用node.js将blob文件上传到S3

node.js - 在nodejs中使用Multer上传文件

node.js - Mongoose 查找操作中的掩码数据

javascript - Momentjs 不打印格式化日期中的秒

node.js - 当 Passport js中的序列化和反序列化调用时

javascript - 如何组织和分离 EmberJS 模板?

Ember.js 和 handlebars 每个助手,带有 subview

ember.js - 在 emblem.js 帮助程序调用中提供多个参数

javascript - 使 Socket.IO 显示浏览器的页面加载指示器(旋转轮)