Theming

Print Values from a Field with a For Loop for Drupal 8, 9, 10, and 11

Last updated
Categories
Up-to-date with minor version
11.0.x

The ability to loop over an array of values in a Twig template and print out each value individually is an important skill for anyone developing themes for Drupal. Common scenarios include: loop over the values of a multiple value field; iterate through a list of links; and display error messages at the top of forms. This tutorial will provide an example of using the Twig for function to iterate over a list, or a subset of a list.

In this tutorial we'll cover how to:

  • Output values from a multi-value field in an unordered list.
  • Add first and last classes to the first and last items in a list by using the Twig loop variable.

By the end of this tutorial you should be able to print out the values of an array as individual list items using a loop in Twig.

Frontend Theming