0

I have the following issue: on the server side I am creating a graph. I would like to display this graph using the Sigma.js library. For reference, the generated data looks for example like this:

{ nodes: 
    [ { id: '423ed89a-491d-416b-9c19-13fcb6db45bc',
        label: 'Nevens Jens',
        x: 0.5935997352935374,
        y: 0.36792555125430226,
        size: 5,
        color: '#fff' } ],
  edges: [] }

In my Express app, I use the following code to render a Jade-page:

app.get('/network', function (req, res) {
    //Function calls to generate graph
    function someCallback(data) {
        res.render('graph', {graphData: data});
    }
}

Next, in my Jade file, I would like to assign this data to a variable so I can use it in a JavaScript file:

script(src='/javascripts/vendor/sigma.min.js')
script.
    var graphData = '#{graphData}'
script(src='/javascripts/graph.js')

My JavaScript file looks like this:

$(document).ready(function () {

    console.log(graphData.nodes);
    console.log(graphData.edges);
    var s = new sigma({
        graph: graphData,
        renderer: {
            container: document.getElementById('graph-container'),
            type: 'canvas'
    }});
    s.refresh();

});

The problem is, when I look at the console in the browser, it shows undefined twice.

Is this a correct way of transferring data to a JavaScript file? Am I doing anything else wrong?

1
  • What version of express.js are you using? Also, if you inspect the HTML, is the data you expect there? Commented May 4, 2015 at 19:33

1 Answer 1

2

You're outputting the data object as a String so you're probably seeing something like var data = '[Object object]' in you outputted html.

Doing something like this in your jade template should fix this issue:

script.
  var graphData = !{graphData}

Let me know that this helps!

Edit: Update with Adrian's comments

Sign up to request clarification or add additional context in comments.

2 Comments

I agree with @Brennan that you are getting [Object object] in your variable, but you should try to keep "processing" logic away from the template. I would use .stringify it on the server, using JSON.stringify(graphData) in the res.render method. If you processo n the server, you need to update the template so your variable looks like this: var graphData = !{graphData}.
An excellent point. I've updated my answer. This is much better. Thanks @Adrian.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.