【问题标题】:How do I loop through an array in a template?如何循环遍历模板中的数组?
【发布时间】:2020-01-12 13:50:21
【问题描述】:

我在一个项目中使用Angular's schematics。

我有一个数字数组:const numbers = [1, 2, 3, 4, 5]

我想在 HTML 模板中打印出来。我通过以下方式传递数组:

export function schematics(_options: Schema): Rule {
  return (tree: Tree, _context: SchematicContext) => {
    const numbers = [1, 2, 3, 4, 5];

    const sourceTemplate = url('./files');
    const sourceParametrizedTemplate = apply(sourceTemplate, [
      template({
        ..._options,
        ...strings,
        numbers
      })
    ]);

    return mergeWith(sourceParametrizedTemplate)(tree, _context);
  };
}

我正在考虑做这样的事情:

index.html

<h1>Numbers</h1>

  <%= for(let n in numbers) { =>

  <p><%= n %></p>

  <%= } %>

但我收到错误 SyntaxError: Unexpected token for。

有谁知道实现它的正确方法是什么?我无法在文档中找到它。

谢谢!

【问题讨论】:

  • 这看起来像经典的 asp 或 asp.net 模板代码。这和角度有什么关系?
  • 我正在使用 Angular 的 Schematics。我会把它说得更清楚,谢谢。

标签: angular angular-schematics


【解决方案1】:

我终于找到了!我不得不在有逻辑的块中使用&lt;% 而不是&lt;%=。

&lt;%= 只能用于您要显示的块。

最终版本:

<h1>Numbers</h1>

  <% for(let n in numbers) { =>

  <p><%= n %></p>

  <% } %>

顺便说一句,我正在寻找的结果是使用 for ... of ... 而不是 for ... in ... 得到的,但它们都有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2015-01-15
    • 2016-07-01
    • 2014-06-08
    • 2020-07-28
    相关资源
    最近更新 更多