0

I am trying to render a array of object (highcharts points). The data should be fine, but when I try to render, I get [object Object] instead of the data themselves.

JSON.stringify() doesn t go well with HTML.

util.inspect, doesn t either, and add data.

toString() give me the same as the rendering.

I don t know what else to try, what I m trying to send is data for a highchart graphic.

Minimal example:

app.js:

var express = require('express'),
    app = express();

app.listen(8080);

app.get('/', function (req, res) {
    var view = 'test.ejs',
        theme = [{name: '1', y: 5}, {name: '2', y: 2}];

    res.render(view, {theme: theme});
    console.log('ok');
});

theme_days.ejs:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    </head>
    <body>
        <script type="text/javascript">
            <%= theme %>
        </script>
    </body>
</html>

Result (as if, toString()):

[object Object],[object Object]

Result with JSON.stringify():

[{&quot;name&quot;:&quot;1&quot;,&quot;y&quot;:5},{&quot;name&quot;:&quot;2&quot;,&quot;y&quot;:2}]

Result with util.inspect:

[ { name: &#39;1&#39;, y: 5 }, { name: &#39;2&#39;, y: 2 } ]

EDIT: I now understand that what s happenning is that ' is escaped to html, is there a way to prevent that?

DrakaSAN
  • 7,673
  • 7
  • 52
  • 94
  • 1
    The eacaping happends in the template level see this for solution http://stackoverflow.com/questions/8547131/how-to-include-html-code-in-a-view – Max Aug 28 '14 at 09:58
  • 1
    @Max: Urg, that and JSON.stringify onstantly resolved the problem... – DrakaSAN Aug 28 '14 at 10:15

2 Answers2

1

I ended up with this:

careful, it is sub optimal:

app.js

var express = require('express'),
    app = express(),
    util = require('util');

app.listen(8080);

app.get('/', function (req, res) {
    var view = 'test.ejs',
        theme = [{"name": "1", "y": 5}, {"name": "2", "y": 2}];//Added "
    console.log(JSON.stringify(theme));
    res.render(view, {theme: JSON.stringify(theme)});
    console.log('ok');
});

test.ejs:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    </head>
    <body>
        <script type="text/javascript">
            var json = '<%= theme %>'.replace(/&quot;/g, '"'),
                theme = JSON.parse(json);
            console.log(theme);
        </script>
    </body>
</html>
DrakaSAN
  • 7,673
  • 7
  • 52
  • 94
1

Why don't you use <%- instead of <%= , and pass object JSON.stringify() method.

The first one will render object in HTML, the second one will render variables (as they are, eval)

Ravi
  • 1,320
  • 12
  • 19