Skip to content

Commit

Permalink
#211: allow a Closure for each attribute on `ListView::itemViewAttrib…
Browse files Browse the repository at this point in the history
…utes()`.
  • Loading branch information
glpzzz committed Sep 8, 2024
1 parent 006c003 commit bcc862c
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/ListView.php
Original file line number Diff line number Diff line change
Expand Up @@ -193,9 +193,15 @@ protected function renderItem(array|object $data, mixed $key, int $index): strin
}

$itemViewAttributes = is_callable($this->itemViewAttributes)
? (array) call_user_func($this->itemViewAttributes, $data, $key, $index, $this)
? (array)call_user_func($this->itemViewAttributes, $data, $key, $index, $this)
: $this->itemViewAttributes;

foreach ($itemViewAttributes as $i => $attribute) {
if (is_callable($attribute)) {
$itemViewAttributes[$i] = $attribute($data, $key, $index, $this);
}
}

return Div::tag()
->attributes($itemViewAttributes)
->content("\n" . $content)
Expand Down
50 changes: 50 additions & 0 deletions tests/ListView/BaseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -278,4 +278,54 @@ public function testClosureForItemViewAttributes(): void
->render(),
);
}

public function testItemViewAttributesWithClosure(): void
{
Assert::equalsWithoutLE(
<<<HTML
<div>
<div class="id-1-key-0-index-0">
<div>Id: 1</div><div>Name: John</div><div>Age: 20</div>
</div>
<div class="id-2-key-1-index-1">
<div>Id: 2</div><div>Name: Mary</div><div>Age: 21</div>
</div>
<div>Page <b>1</b> of <b>1</b></div>
</div>
HTML,
ListView::widget()
->itemView(dirname(__DIR__) . '/Support/view/_listview.php')
->itemViewAttributes([
'class' => static fn(array $data, $key, $index) => "id-{$data['id']}-key-{$key}-index-{$index}",
])
->dataReader($this->createOffsetPaginator($this->data, 10))
->separator(PHP_EOL)
->render(),
);
}

public function testClosureForItemViewAttributesWithClosure(): void
{
Assert::equalsWithoutLE(
<<<HTML
<div>
<div class="id-1-key-0-index-0">
<div>Id: 1</div><div>Name: John</div><div>Age: 20</div>
</div>
<div class="id-2-key-1-index-1">
<div>Id: 2</div><div>Name: Mary</div><div>Age: 21</div>
</div>
<div>Page <b>1</b> of <b>1</b></div>
</div>
HTML,
ListView::widget()
->itemView(dirname(__DIR__) . '/Support/view/_listview.php')
->itemViewAttributes(static fn (array $data, $key, $index) => [
'class' => static fn(array $data, $key, $index) => "id-{$data['id']}-key-{$key}-index-{$index}",
])
->dataReader($this->createOffsetPaginator($this->data, 10))
->separator(PHP_EOL)
->render(),
);
}
}

0 comments on commit bcc862c

Please sign in to comment.