diff --git a/src/Html/Builder.php b/src/Html/Builder.php index 83e16ed..b825b2d 100644 --- a/src/Html/Builder.php +++ b/src/Html/Builder.php @@ -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 */ @@ -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(); } /** @@ -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; + } } diff --git a/tests/Html/Builder/BuilderTest.php b/tests/Html/Builder/BuilderTest.php index 1b61ef2..32071e8 100644 --- a/tests/Html/Builder/BuilderTest.php +++ b/tests/Html/Builder/BuilderTest.php @@ -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() + ); + } } diff --git a/tests/TestComponents/test-builder-script.blade.php b/tests/TestComponents/test-builder-script.blade.php new file mode 100644 index 0000000..a3ef460 --- /dev/null +++ b/tests/TestComponents/test-builder-script.blade.php @@ -0,0 +1 @@ +console.log({ tableId: @js($tableId ?? 'noneset'), message: @js($message) });