主题
Layout
#[Layout] 属性指定全页面组件应使用哪个 Blade 布局,允许您在每个组件基础上自定义布局。
基本用法
将 #[Layout] 属性应用到全页面组件以使用特定布局:
php
<?php // resources/views/pages/posts/⚡index.blade.php
use Livewire\Attributes\Layout;
use Livewire\Component;
use App\Models\Post;
#[Layout('layouts.dashboard')] // [tl! highlight]
new class extends Component
{
public function posts()
{
return Post::all();
}
};
?>
<div>
<h1>帖子</h1>
@foreach ($this->posts as $post)
<div>{{ $post->title }}</div>
@endforeach
</div>此组件将使用 resources/views/layouts/dashboard.blade.php 布局而不是默认布局进行渲染。
默认布局
默认情况下,Livewire 使用 config/livewire.php 文件中指定的布局:
php
'layout' => 'components.layouts.app',#[Layout] 属性会覆盖特定组件的此默认设置。
向布局传递数据
您可以使用数组语法向布局传递额外数据:
php
#[Layout('layouts.dashboard', ['title' => 'Posts Dashboard'])] // [tl! highlight]
new class extends Component
{
// ...
};在您的布局文件中,$title 变量将可用:
blade
<!DOCTYPE html>
<html>
<head>
<title>{{ $title ?? '我的应用' }}</title>
</head>
<body>
{{ $slot }}
</body>
</html>替代方法:使用 layout() 方法
除了使用属性外,您还可以在 render() 方法中使用 layout() 方法:
php
<?php // resources/views/pages/posts/⚡index.blade.php
use Livewire\Component;
new class extends Component
{
public function render()
{
return view('livewire.posts.index')
->layout('layouts.dashboard', ['title' => 'Posts']); // [tl! highlight]
}
};对于不需要 render() 方法的单文件组件,属性方法更简洁。
为每个页面使用不同的布局
一个常见模式是为应用程序的不同部分使用不同的布局:
php
// 管理页面
#[Layout('layouts.admin')]
new class extends Component { }
// 营销页面
#[Layout('layouts.marketing')]
new class extends Component { }
// 仪表板页面
#[Layout('layouts.dashboard')]
new class extends Component { }何时使用
在以下情况下使用 #[Layout]:
- 应用程序中有多个布局(管理、营销、仪表板等)
- 特定页面需要与默认布局不同的布局
- 您正在构建全页面组件(而不是常规组件)
- 您希望将布局配置保持在组件定义附近
仅适用于全页面组件
#[Layout] 属性仅适用于全页面组件。在其他视图中渲染的常规组件不使用布局。
了解更多
有关全页面组件和布局的更多信息,请参阅页面文档。