Eray
Eray

Reputation: 7128

Parsing arrays on JADE Template Engine

I'm using JADE template engine with ExpressJS.

sending this array to JADE template

var data = {
    "labels" : ["Label 1", "Label 2"]
};
res.render('index', {data: data});

And my JADE file looks like this:

script(type='text/javascript').
  var options = {
  labels: [#{data.labels}],
  ...
  };

As you see I'm trying to get data.labels values to inline <script> block of my JADE file. But output is like this:

<script type="...">
var options = {
      labels: [Label 1, Label 2], <-- invalid syntax
      ...
      };

it must be like this:

<script type="...">
var options = {
      labels: ["Label 1", "Label 2"], <-- valid syntax
      ...
      };

What should I do to use an array directly in JADE file?

Upvotes: 1

Views: 219

Answers (1)

Amadan
Amadan

Reputation: 198334

JSON makes things right:

// magic of JSON.stringify:
var src = "script var labels = !{JSON.stringify(labels)}";

// let's try and render it:
var data = {
    "labels" : ["Label 1", "Label 2"]
};
var fn = jade.compile(src);

var html = fn(data);

console.log(html);
// output: <script>var labels = ["Label 1","Label 2"]</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jade/1.11.0/jade.min.js"></script>

Upvotes: 3

Related Questions