42

I have a pretty heavyweight query on the server that results in a new page render, and I'd like to pass along some of the results of the query to the client (as a javascript array of objects). This is basically so I don't have to do a separate JSON query later to get the same content (which is mostly static). The data will be useful eventually, but not initially so I didn't put it directly into the document.

app.get('/expensiveCall', function(req, res) {
    // do expensive call
    var data = veryExpensiveFunction();
    res.render('expensiveCall.jade', {
        locals: {
                data: data,
                }
        });
    });
});

data is a array of objects and only some are initially used. I'd like to pass either the entirety of data over or some subsets (depending on the situation). My jade looks like normal jade, but I would like to include something like

<script type="text/javascript">
var data = #{data};
</script>

but this doesn't work (it's an array of objects).

killermonkeys
  • 445
  • 1
  • 5
  • 6

1 Answers1

89

You can't inline a JS object like that, but you can JSON.stringify it before:

<script type="text/javascript">
  var data = !{JSON.stringify(data)};
</script>
Adrien
  • 9,551
  • 3
  • 26
  • 27
  • 1
    Sorry should have said that earlier: jade escapes all emitted content which means I'd also have to unescape it, and it's not clear how to turn off escaping. I think there is some way to do with within express, but I'm not sure how. I may just switch to a different template engine but it means forking code :-(. – killermonkeys Oct 07 '11 at 03:03
  • 10
    If you use `!{}` instead of `#{}` the escaping should be turned off. – Adrien Oct 07 '11 at 11:49
  • ack! I didn't catch that, makes sense. Thanks! – killermonkeys Oct 07 '11 at 16:05
  • Is this good practice or am I missing another way of passing json to client? – Jeremy Knees Nov 07 '14 at 13:18
  • Will the value of the variable get updated if the view is re-rendered. – user1736947 Apr 08 '15 at 17:46
  • @Adrien +1 for being helpful, however your code will render the stringified JSON straight into the JavaScript causing a syntax error. You easily resolve this by encasing the !{} with quotes. – Crazy Redd Oct 30 '16 at 08:34
  • Thanks you for nice solution – haotang Sep 15 '17 at 04:32