Laravel Blade 模板指南
Blade 模板引擎参考:布局、部分视图、组件、插槽、指令、条件和循环。
1. 布局与继承
<!-- layouts/app.blade.php -->
<!DOCTYPE html>
<html>
<head><title>@yield('title', config('app.name'))</title>@stack('styles')</head>
<body>
@include('partials.nav')
<main>@yield('content')</main>
@stack('scripts')
</body>
</html>
<!-- articles/show.blade.php -->
@extends('layouts.app')
@section('title', $article->title)
@section('content')
<h1>{{$article->title}}</h1>
{!! $article->content_html !!}
@endsection
2. 组件
<!-- components/alert.blade.php -->
@props(['type' => 'info', 'dismissible' => false])
<div class="alert alert-{{$type}}">
{{$slot}}
@if($dismissible)
<button class="btn-close" data-bs-dismiss="alert"></button>
@endif
</div>
<!-- 使用 -->
<x-alert type="success" :dismissible="true">发布成功!</x-alert>
3. 条件与循环
@if($user->isAdmin()) <a href="/admin">管理面板</a> @endif
@auth <span>你好,{{auth()->user()->name}}</span> @endauth
@guest <a href="/login">登录</a> @endguest
@can('update', $article)
<a href="/articles/{{$article->id}}/edit">编辑</a>
@endcan
@forelse($articles as $article)
<p>{{$loop->iteration}}. {{$article->title}}</p>
@empty
<p>暂无文章。</p>
@endforelse
4. 表单与 CSRF
<form method="POST" action="/articles">
@csrf
@method('PUT')
<input type="text" name="title" value="{{old('title', $article->title)}}">
@error('title')
<span class="error">{{$message}}</span>
@enderror
<button type="submit">保存</button>
</form>