简体   繁体   中英

Accessing arrays in Nunjucks template within <script>

I have an array on server side, which adds the number 1 every 10 minutes. eg [1, 1, 1, 1....]

I send this to the template as follows (data() is the array as my example above) :

router.get('/', (req, res) => {
  return res.render('index', {
    results: data(),
  });
});

I have a script on the template which renders a graph. For this to work, the array needs to be accessible in the script.

When I access the array by:

var results = "{{ results }}";

The array ends up like:

["1, 1, 1, 1"]

I need the array without the double quotes. Is this possible?

[1, 1, 1, 1]

You could change it on the server or the client - I'd say let's just do it on the client side.

The entire array is made up of 1 spot that has all the values separated by commas.
We first grab that chunk of data with (["1, 1, 1, 1"][0]) - this will return just the first spot in the array with all of the data.

Then we clear out any spaces (.replace(/\\s/g,'').

Turn it into a true array (split(",")).

Then turn each of those string numbers into true numbers (.map(function(e){return Number(e);}))

remove: .map(function(e){return Number(e);}) if you don't care if the numbers are strings or not.

 var results = ["1, 1, 1, 1"][0]; var result = results.replace(/\\s/g,'').split(",").map(function(e){return Number(e);}); console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM