Yeoman 在模板中循环

Yeoman looping in template

我正在尝试使用 yeoman 获取此 JSON 文件:

{
  "models": {
    "user": {
      "properties": [
        {
          "name": {
            "type": "string"
          },
          "surname": {
            "type": "string"
          },
          "id": "number"
        }
      ]
    }
  }
}

然后把它变成类似这样的东西:

Class User {
  name : string
  surname : string
  id : number
}

是否可以在模板中进行某种形式的循环?这是我的想法...

  export class <%= entityName %> extends Model   {
      <% forEach (property in props) { %>
         <%= property.name %> : <% property.type %>;
      <% } %>
  }

我认为您不能在模板中使用那种循环。你可以做的是在你的脚本文件中有一个 helpermethod 来将你的 json 文件的内容生成到一个变量中,然后将该变量添加到你的模板中。

模板语言可以运行任何JS代码。所以只需在数组 (arr.forEach())

上使用正常的 for 循环或迭代方法
export class <%= entityName %> extends Model   {
    <% for (property of props) { %>
         <%= property.name %> : <% property.type %>;
    <% } %>
}

Yeoman 正在使用 ejs as template engine. Visit their website for more information on the supported features