javascript - Node Js Express 遍历数组

标签 javascript node.js express hogan.js

我已将 shell 命令的 STDOUT 拆分为一个数组,并使用 express 将其传递给 hogan View 引擎。

下面是来自路由器文件 - index.js

/* Test Shell Execute. */
router.get('/shell', function(req, res){
  exec('ls -1', function (error, stdout, stderr) {
       result = stdout.toString().split("\n");
       res.render('shell', { title: "File Explorer",
          array1: result[0],
          array2: result[1],
          array3: result[2],
          array4: result[3],
          array5: result[4],
          error: error,
          stderr: stderr 
     });
  });
});

这工作正常,但是我不想手动发送数组中的每个项目,而是想迭代 View 端的项目,然后输出。但是我使用的是 Hogan View 引擎,它似乎根本无法识别脚本标签。

这是我查看的 shell.hjs 文件。

<!DOCTYPE html>
<html>
  <head>
    <title>{{ title }}</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1>{{ title }}</h1>
    <p>Welcome to {{ title }}</p>
     <p>Array1 =  {{ array1 }}</p>
     <p>Array2 =  {{ array2 }}</p>
     <p>Array3 =  {{ array3 }}</p>
     <p>Array4 =  {{ array4 }}</p>
     <script>
     for(var i = 0; i > result.length; i++  ) {
         document.write('<p>' + result[i] + '</p>')
     }
     </script>
  </body>
</html>

问题:我做错了什么?最好/最简单的方法是什么?

最佳答案

由于 hogan.js 基于 Mustache.js,因此最好尝试将数组转换为对象。试试这个:

router.get('/shell', function(req, res){
  exec('ls -1', function (error, stdout, stderr) {
    result = stdout.split("\n"),
             filesArray = [];
    result.map(function (file, index) {
      filesArray.push({index: ++index, file: file});
    });
    res.render('shell', { title: "File Explorer",
      result: filesArray,
      error: error,
      stderr: stderr 
    });
  });
});

并且,在您的模板中:

<!DOCTYPE html>
<html>
  <head>
    <title>{{ title }}</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1>{{ title }}</h1>
    <p>Welcome to {{ title }}</p>
    <ul>
      {{#result}}
      <li>Array{{index}} = {{file}}</li>
      {{/result}}
    </ul>
  </body>
</html>

关于javascript - Node Js Express 遍历数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24254538/

相关文章:

javascript - 返回到在 Express 中进行重定向调用的文件

javascript - 带有错误处理功能的外部扭曲函数

javascript - 在 jQuery UI 中获取 ul 和 li 值可在拖放时排序

javascript - OpenLayers MVT 图层并设置样式

javascript - 当客户端互联网关闭时的 Socket.io

node.js - 如何使用 Nodemon 监控符号链接(symbolic link)模块?

javascript - jQuery 创建新数组并将旧数组加倍

javascript - 获取按钮文本值以确定变量值

node.js - 将客户端和服务器 Nodejs 应用程序部署到 Azure

node.js - express 的 hapi request.state 的等效部分是什么?