Skip to content

Commit

Permalink
DOC Document ability to loop over arrays in templates (#517)
Browse files Browse the repository at this point in the history
  • Loading branch information
GuySartorelli authored May 24, 2024
1 parent 0222e86 commit 72d0ed5
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
18 changes: 11 additions & 7 deletions en/02_Developer_Guides/01_Templates/01_Syntax.md
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ include.
## Looping over lists

The `<% loop %>` tag is used to iterate or loop over a collection of items such as [DataList](api:SilverStripe\ORM\DataList) or an [ArrayList](api:SilverStripe\ORM\ArrayList)
The `<% loop %>` tag is used to iterate or loop over a collection of items such as a native PHP array, a [DataList](api:SilverStripe\ORM\DataList), or an [ArrayList](api:SilverStripe\ORM\ArrayList)
collection.

```ss
Expand Down Expand Up @@ -589,16 +589,20 @@ $Pages->First
```

You can also use the `$Me` variable, which outputs the current object in scope by calling `forTemplate()` on the object.
This is especially helpful when you want to directly render items in a list you're looping over.

```ss
<%-- app/templates/App/PageType/Layout/HomePage.ss --%>
> [!WARNING]
> If the object does not have a `forTemplate()` method implemented, this will throw an error.
<%-- calls forTemplate() on the current object in scope and prints Page: Home --%>
$Me
```ss
<% loop $Pages %>
<%-- calls forTemplate() on the current object in scope and prints Page: Home --%>
$Me
<% end_loop %>
```

> [!WARNING]
> If the object does not have a `forTemplate()` method implemented, this will throw an error.
> [!NOTE]
> If you use `$Me` in a control block such as `<% if $Me %>` or `<% loop $Me %>` it references the item directly rather than calling `forTemplate()` on it.
## Comments

Expand Down
2 changes: 2 additions & 0 deletions en/08_Changelogs/6.0.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ CanonicalURLMiddleware::singleton()->setEnabledEnvs([

### Other new features

- Native indexed PHP arrays can now be passed into templates and iterated over with `<% loop $MyArray %>`. Under the hood they are wrapped in [`ArrayList`](api:SilverStripe\View\ViewableData), so you can get the count using `$Count` and use `<% if $ArrayList %>` as a shortcut for `<% if $ArrayList.Count %>`. Other functionality from `ArrayList` such as filtering and sorting cannot be used on arrays since they don't have keys to filter or sort against.

## Bug fixes

This release includes a number of bug fixes to improve a broad range of areas. Check the change logs for full details of these fixes split by module. Thank you to the community members that helped contribute these fixes as part of the release!
Expand Down

0 comments on commit 72d0ed5

Please sign in to comment.