Blade 구성 요소 만들기 - Laravel updated_at: 2024-12-14 03:43

Laravel Blade 컴포넌트 만들기

Blade 컴포넌트는 자주 사용하는 UI 템플릿을 재사용 가능한 형태로 캡슐화할 수 있는 기능입니다. @include와 비슷하지만, 컨트롤러처럼 클래스 로직을 포함할 수 있어 더 유연하고 강력합니다.

참고: 단순한 템플릿 삽입은 @include를 사용할 수 있지만, 이 경우에는 PHP를 직접 사용해야 하므로 구조화된 컴포넌트에 비해 관리가 어렵습니다.
예: include를 사용한 사용자 정의 Pagination 예제


1. 기본 컴포넌트 생성

컴포넌트 생성 명령어

php artisan make:component Alert

생성되는 파일 구조

  • 클래스 파일: /app/View/Components/Alert.php
  • 뷰 파일: /resources/views/components/alert.blade.php

/app/View/Components/Alert.php

<?php

namespace App\View\Components;

use Illuminate\View\Component;

class Alert extends Component
{
    public function __construct()
    {
        // 초기화 로직 (없으면 비워둡니다)
    }

    public function render()
    {
        return view('components.alert');
    }
}

/resources/views/components/alert.blade.php

<div>
    <!-- Sample Alert Component -->
    This is a basic alert box.
</div>

Blade에서 컴포넌트 사용하기

<!-- sample-view.blade.php -->
<x-alert />

2. 파라미터를 받는 컴포넌트 확장 예제

컴포넌트에 데이터를 전달하고 출력하는 예제를 살펴보겠습니다.

Alert 컴포넌트 수정

/app/View/Components/Alert.php

<?php

namespace App\View\Components;

use Illuminate\View\Component;

class Alert extends Component
{
    public $type;
    public $message;
    public $var;

    public function __construct($type, $message, $var = null)
    {
        $this->type = $type;
        $this->message = $message;
        $this->var = $var;
    }

    public function render()
    {
        return view('components.alert');
    }
}

/resources/views/components/alert.blade.php

<div class="c-alert c-alert--{{ $type }}" role="alert">
    <p class="c-alert__message">{{ $message }}</p>
    @if ($var)
        <p class="c-alert__var">{{ $var }}</p>
    @endif
</div>

Blade에서 데이터 전달 예시

@php
    $var = 'my var';
@endphp

<x-alert type="info" message="Please try again." :var="$var" />

주의사항: 변수명을 snake_case 형태로 사용할 경우 컴포넌트에서 정상적으로 전달되지 않을 수 있으므로, camelCase 또는 kebab-case를 사용하세요.


3. 클래스 없이 간단한 컴포넌트 만들기 (Anonymous Component)

간단한 출력은 별도의 클래스 없이 뷰 파일만으로도 컴포넌트를 만들 수 있습니다.

예제 파일

resources/views/components/message.blade.php

@props(['message'])

<p>Your message is: {{ $message }}</p>

사용 방법

<x-message message="Welcome to Story" />

정리

구분 특징 사용 예
@include 간단한 템플릿 삽입 반복적인 HTML 조각
컴포넌트(Class 포함) 재사용 + 로직 포함 경고창, 카드 UI 등
Anonymous 컴포넌트 로직 없이 단순 출력 단일 메시지, 라벨 등

4. 동적 컴포넌트(Dynamic Components)

Laravel에서는 <x-dynamic-component>를 사용하여 컴포넌트를 동적으로 렌더링할 수 있습니다. 이는 컴포넌트 이름이 실행 중에 결정되어야 하는 경우 유용합니다.

사용 예시

@php
    $componentName = 'alert';
@endphp

<x-dynamic-component :component="$componentName" type="warning" message="Dynamic warning!" />

위 코드는 <x-alert type="warning" message="...">와 동일하게 작동합니다.

동적 이름 예시

@php
    $type = 'success';
    $componentName = 'components.status-' . $type;
@endphp

<x-dynamic-component :component="$componentName" message="It worked!" />

참고: :component에 전달되는 값은 컴포넌트 경로 또는 이름(resources/views/components/ 기준)입니다.


평점을 남겨주세요
평점 : 5.0
총 투표수 : 1

질문 및 답글