Search code examples
javascriptnode.jsd3.jsdust.jsdust-helpers

What would be a good approach for providing d3 capability in a dust-helper?


Right now I've been considering writing a dust-helper that renders barcharts into dust files server-side using a custom dust-helper and the d3 module for node. I was wondering if there was a better way than to construct some sort of context object like this to pass to the dust renderer:

{
  padding: {
    top: integer,
    right: integer,
    bottom: integer,
    left: integer
  },
  width: integer,
  height: integer,
  data: [datum, ...],
  x: {
    scale: {
      type: string, // 'linear', 'time', 'ordinal'
      range: 'extent', // optionally [lower, upper]
      tick: { // if applicable
        format: string, // d3 number format for linear scale
                        // d3 time format for time scale
        args: integer | [interval, integer]
      }
    },
    value: string, // datum[value] used for x-axis
  },
  y: {
    ...
  }
}

And so on, then have d3 use this scheme to render the customized components and return the SVG markup as a string. This seems like a very verbose option to me, with a lot of requirement to add more and more attributes that bloat the context until it becomes too messy to manage well, which is why I was wondering if there was a better approach by perhaps splitting dust helpers for individual components of d3.


Solution

  • I've been thinking about it and the best way I think to go about using d3 as a dust filter instead as the following:

    dust.filters.d3 = function(value) {
        var node = d3.select(value).node();
    
        if (node) {
            return node.outerHTML;
        }
    
        return 'd3 selection not found';
    };
    

    And just running the d3 code before starting the dust rendering.