Skip to content

Instantly share code, notes, and snippets.

@PH7-Jack
Created August 17, 2021 14:12
Show Gist options
  • Save PH7-Jack/0436c2ef598bd0458db9733270709109 to your computer and use it in GitHub Desktop.
Save PH7-Jack/0436c2ef598bd0458db9733270709109 to your computer and use it in GitHub Desktop.
Livewire Component Title macro
<?php
namespace App\Providers;
use App\Macros\ViewMacros;
use Illuminate\Support\ServiceProvider;
use Illuminate\View\View;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
View::mixin(new ViewMacros());
}
}
public function render()
{
// default layout
return view('livewire.view')->title('My Title');
// custom layout
// the layout must become first
return view('livewire.view')->layout('layouts.my-layout')->title('My Title');
}
<?php
namespace App\Macros;
class ViewMacros
{
public function title()
{
return function (string $title) {
data_set($this->livewireLayout, 'params.title', $title);
return $this;
};
}
}
<?php
namespace Tests\Unit\ViewMacro;
use Illuminate\Support\Facades\Route;
use Livewire\{Component, CreateBladeView, Livewire};
use Tests\TestCase;
class ViewTitleMacroTest extends TestCase
{
/** @test */
public function it_should_render_title_inside_layout()
{
Livewire::component(TitledComponent::class);
Route::get('/foo', TitledComponent::class);
$this->get('/foo')
->assertSee('My Title')
->assertSee('Titled Component')
->assertDontSee('Without Title');
}
}
class TitledComponent extends Component
{
public function render()
{
return app('view')
->make(CreateBladeView::fromString('<div>Titled Component</div>'))
->layout('layouts.guest') // only for testing purposes
->title('My Title');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment