Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion src/Html/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ class Builder

protected array $additionalScripts = [];

protected array $templateData = [];

public function __construct(public Repository $config, public Factory $view, public HtmlBuilder $html)
{
/** @var array $defaults */
Expand Down Expand Up @@ -159,7 +161,13 @@ protected function template(): string

$template = $this->template ?: $configTemplate;

return $this->view->make($template, ['editors' => $this->editors, 'scripts' => $this->additionalScripts])->render();
return $this->view->make(
$template,
array_merge(
['editors' => $this->editors, 'scripts' => $this->additionalScripts],
$this->templateData,
)
)->render();
}

/**
Expand Down Expand Up @@ -292,4 +300,15 @@ public function getAdditionalScripts(): array
{
return $this->additionalScripts;
}

public function setTemplateData(array|\Closure $data = []): static
{
if ($data instanceof \Closure) {
$data = $data($this) ?? [];
}

$this->templateData = $data;

return $this;
}
}
27 changes: 27 additions & 0 deletions tests/Html/Builder/BuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -303,4 +303,31 @@ public function it_ignores_unauthorized_columns(): void

$this->assertCount(1, $builder->getColumns());
}

#[Test]
public function it_can_set_template_data(): void
{
$builder = $this->getHtmlBuilder()
->addScript('test-builder-script')
->setTemplateData(['message' => 'Test Message']);

$this->assertStringContainsString(
"console.log({ tableId: 'noneset', message: 'Test Message' });",
$builder->generateScripts()->toHtml()
);

$builder
->setTableId('my-table')
->setTemplateData(function (Builder $builder): array {
return [
'tableId' => $builder->getTableId(),
'message' => 'Set Template Data Using Callback',
];
});

$this->assertStringContainsString(
"console.log({ tableId: 'my-table', message: 'Set Template Data Using Callback' });",
$builder->generateScripts()->toHtml()
);
}
}
1 change: 1 addition & 0 deletions tests/TestComponents/test-builder-script.blade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
console.log({ tableId: @js($tableId ?? 'noneset'), message: @js($message) });