1

I'm using Node + Express.js. One of my routes renders a Handlebars template and its context. The relevant part:

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

My question: Within that activity.hbs template, how to can I use D3 to create a plot from the my_data JSON object. In the relevant part of activity.hbs I have tried

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

I added the Helper after reading this question. When I try to render the view, it gives an Error:

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

Is using a Helper the right way to approach this problem? How can I get D3 to read my context object?

Community
  • 1
  • 1
idclark
  • 948
  • 1
  • 8
  • 27

1 Answers1

1

The problem I think is in your helper definition, basically you are defining the helper in the wrong place. To define an helper, based on the documentation of express3-handlebars you have to register it in your express app code:

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');
MarcoL
  • 9,829
  • 3
  • 37
  • 50