Layout
#[Layout] 属性指定全页组件应使用哪个 Blade 布局,允许你按组件自定义布局。
基本用法
将 #[Layout] 属性应用到全页组件以使用特定布局:
php
<?php // resources/views/pages/posts/⚡index.blade.php
use Livewire\Attributes\Layout;
use Livewire\Attributes\Computed;
use Livewire\Component;
use App\Models\Post;
new #[Layout('layouts::dashboard')] class extends Component { // [tl! highlight]
#[Computed]
public function posts()
{
return Post::all();
}
};
?>
<div>
<h1>Posts</h1>
@foreach ($this->posts as $post)
<div wire:key="{{ $post->id }}">{{ $post->title }}</div>
@endforeach
</div>该组件将使用 resources/views/layouts/dashboard.blade.php 布局渲染,而不是默认布局。
默认布局
默认情况下,Livewire 使用 config/livewire.php 文件中指定的布局:
php
'component_layout' => 'layouts::app',#[Layout] 属性会为特定组件覆盖此默认值。
向布局传递数据
你可以使用数组语法向布局传递额外数据:
php
new #[Layout('layouts::dashboard', ['title' => 'Posts Dashboard'])] class extends Component { // [tl! highlight]
// ...
};在布局文件中,$title 变量将可用:
blade
<!DOCTYPE html>
<html>
<head>
<title>{{ $title ?? 'My App' }}</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 $this->view()
->layout('layouts::dashboard', ['title' => 'Posts']); // [tl! highlight]
}
};对于不需要 render() 方法的单文件组件,属性方式更简洁。
按页面使用不同布局
常见做法是为应用的不同部分使用不同布局:
php
// Admin pages
new #[Layout('layouts::admin')] class extends Component { }
// Marketing pages
new #[Layout('layouts::marketing')] class extends Component { }
// Dashboard pages
new #[Layout('layouts::dashboard')] class extends Component { }何时使用
在以下情况使用 #[Layout]:
- 应用中有多个布局(管理、营销、仪表盘等)
- 特定页面需要不同于默认的布局
- 正在构建全页组件(而非普通组件)
- 希望将布局配置放在组件定义附近
INFO
仅适用于全页组件
#[Layout] 属性仅适用于全页组件。在其他视图中渲染的普通组件不使用布局。
了解更多
关于全页组件与布局的更多信息,请参阅页面文档。
参考
php
#[Layout(
string $name,
array $params = [],
)]| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
$name | string | 必填 | 要使用的 Blade 布局名称 |
$params | array | [] | 传给布局的额外数据 |