Chuyển đến nội dung chính

レッスン 3: ブレード テンプレートとフロントエンド

ブレードの構文、コンポーネント、レイアウト。ブレード ディレクティブ、カスタム ディレクティブ。アセットのバンドル (Vite)。 Tailwind CSS の統合。匿名コンポーネント、動的コンポーネント。

💻 プログラミング — レッスン 3 レッスン 3: ブレード テンプレートとフロントエンド

Laravel: 基本から上級まで

パート 1: Laravel の基礎

xdev.asia

1. ブレードの構文

{{-- Hiển thị data (auto-escaped) --}}
<h1>{{ $product->name }}</h1>
<p>{!! $product->html_description !!}</p>

{{-- Conditionals --}}
@if($products->count() > 0)
    @foreach($products as $product)
        <div>{{ $product->name }} - {{ number_format($product->price) }}đ</div>
    @endforeach
@else
    <p>Không có sản phẩm nào.</p>
@endif

{{-- Auth directives --}}
@auth
    <p>Xin chào, {{ auth()->user()->name }}</p>
@endauth

@guest
    <a href="/login">Đăng nhập</a>
@endguest

2. レイアウトとコンポーネント

{{-- resources/views/layouts/app.blade.php --}}
<!DOCTYPE html>
<html>
<head>
    <title>@yield('title') - My App</title>
    @vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body>
    <x-header />
    <main>{{ $slot }}</main>
    <x-footer />
</body>
</html>

{{-- resources/views/products/index.blade.php --}}
<x-app-layout>
    @section('title', 'Sản phẩm')
    <h1>Danh sách sản phẩm</h1>
    @foreach($products as $product)
        <x-product-card :product="$product" />
    @endforeach
    {{ $products->links() }}
</x-app-layout>

3. ブレードのコンポーネント

// app/View/Components/ProductCard.php
namespace App\View\Components;

use Illuminate\View\Component;

class ProductCard extends Component
{
    public function __construct(
        public readonly Product $product,
        public bool $showPrice = true,
    ) {}

    public function render()
    {
        return view('components.product-card');
    }
}
{{-- resources/views/components/product-card.blade.php --}}
<div {{ $attributes->merge(['class' => 'card p-4 rounded-lg shadow']) }}>
    <h3>{{ $product->name }}</h3>
    @if($showPrice)
        <p class="text-lg font-bold">{{ number_format($product->price) }}đ</p>
    @endif
    {{ $slot }}
</div>

4.Vite & Tailwind CSS

// vite.config.js
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

export default defineConfig({
    plugins: [
        laravel({
            input: ['resources/css/app.css', 'resources/js/app.js'],
            refresh: true,
        }),
    ],
});

次の記事: 雄弁な ORM と関係。