简体   繁体   中英

How do I loop through an array in a template?

I am using Angular's schematics in a project.

I have an array of numbers: const numbers = [1, 2, 3, 4, 5]

And I want to print them out in an HTML template. I am passing the array in the following way:

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);
  };
}

I was thinking about doing something like this:

index.html

<h1>Numbers</h1>

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

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

  <%= } %>

But I get the error SyntaxError: Unexpected token for .

Does anyone know what is the correct way of achieving it? I was not able to find it in the documentation.

Thank you!

I finally found it! I had to use <% instead of <%= in the blocks with logic.

<%= should only be used for blocks that you want to display.

Final version:

<h1>Numbers</h1>

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

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

  <% } %>

By the way, the result I was looking for I got it using for ... of ... instead of for ... in ... , but they both work.

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