Created
August 17, 2021 14:12
-
-
Save ph7jack/0436c2ef598bd0458db9733270709109 to your computer and use it in GitHub Desktop.
Livewire Component Title macro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Macros; | |
class ViewMacros | |
{ | |
public function title() | |
{ | |
return function (string $title) { | |
data_set($this->livewireLayout, 'params.title', $title); | |
return $this; | |
}; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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