0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Blade と Twig の書き方の違いをまとめる

0
Last updated at Posted at 2025-12-03

Twigの予習です。
普段はBladeを利用しているので、それに合わせて対応するものを書き出した。

変数の表示

内容 Blade Twig
変数表示 {{ $name }} {{ name }}

コメント

内容 Blade Twig
コメント {{-- コメント --}} {# コメント #}

IF文

Blade

@if($user->isAdmin())
    管理者
@elseif($user->isGuest())
    ゲスト
@else
    一般ユーザー
@endif

Twig

{% if user.isAdmin %}
    管理者
{% elseif user.isGuest %}
    ゲスト
{% else %}
    一般ユーザー
{% endif %}

ループ(foreach / for)

Blade

@foreach($users as $user)
    {{ $user->name }}
@endforeach

Twig

{% for user in users %}
    {{ user.name }}
{% endfor %}

テンプレート継承(レイアウト)

Blade

レイアウト側:

<title>@yield('title')</title>

@yield('content')

子ビュー:

@extends('layouts.app')

@section('title', 'ページタイトル')

@section('content')
    本文
@endsection

Twig

レイアウト側:

<title>{% block title %}デフォルト{% endblock %}</title>

{% block content %}{% endblock %}

子ビュー:

{% extends "layouts/app.html.twig" %}

{% block title %}ページタイトル{% endblock %}

{% block content %}
    本文
{% endblock %}

include(部品化)

Blade

@include('components.alert', ['message' => '保存しました'])

Twig

{% include 'components/alert.html.twig' with { 'message': '保存しました' } %}

URLの生成

内容 Blade Twig
ルート URL {{ route('users.show', $id) }} {{ path('users_show', {id: user.id}) }}

条件付きクラス

Blade

<div class="{{ $active ? 'is-active' : '' }}">

Twig

<div class="{{ active ? 'is-active' : '' }}">

フィルタ

Blade は関数かクラスを直接呼ぶ。

{{ Str::upper($name) }}
{{ $date->format('Y-m-d') }}

Twig

{{ name | upper }}
{{ date | date('Y-m-d') }}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?