简体   繁体   English

在 Nunjucks 模板中访问数组<script>

[英]Accessing arrays in Nunjucks template within <script>

I have an array on server side, which adds the number 1 every 10 minutes.我在服务器端有一个数组,每 10 分钟添加一个数字 1。 eg [1, 1, 1, 1....]例如 [1, 1, 1, 1 ....]

I send this to the template as follows (data() is the array as my example above) :我将其发送到模板如下(data() 是我上面示例中的数组)

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.整个数组由 1 个点组成,所有值以逗号分隔。
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.我们首先使用 (["1, 1, 1, 1, 1"][0]) 获取该数据块 - 这将仅返回包含所有数据的数组中的第一个点。

Then we clear out any spaces (.replace(/\\s/g,'').然后我们清除所有空格 (.replace(/\\s/g,'')。

Turn it into a true array (split(",")).把它变成一个真正的数组(split(","))。

Then turn each of those string numbers into true numbers (.map(function(e){return Number(e);}))然后将每个字符串数字转换为真实数字(.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.删除: .map(function(e){return Number(e);}) 如果你不关心数字是否是字符串。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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