输出数据

  1. {{ $variable }}
  2. // 等价于
  3. <?= htmlentities( $variable ); ?>
  4. // 如果不想被转义
  5. {!! $variable !!}

ps: 一些前端框架也使用了 {{}} 的语法,例如 layui, 这就产生了冲突,laravel 提供了 @ 符号,来告诉 blade 引擎,哪些 {{}} 不做解析处理,保留原始形态。

// Parsed as Blade; the value of $bladeVariable is echoed to the view
{{ $bladeVariable }}

// @ is removed and "{{ handlebarsVariable }}" echoed to the view directly
@{{ handlebarsVariable }}

控制结构

条件

@if (count($talks) === 1)
    There is one talk at this time period.
@elseif (count($talks) === 0)
    There are no talks at this time period.
@else
    There are {{ count($talks) }} talks at this time period.
@endif


// 等价于 if( !$user->hasPaid() )
@unless ($user->hasPaid()) 
    You can complete your payment by switching to the payment tab.
@endunless

循环

@for ($i = 0; $i < $talk->slotsCount(); $i++)
    The number is {{ $i }}<br>
@endfor

@foreach ($variable as $key => $value) 
    <li> {{ $key }} '==>' {{ $value }} </li>
@endforeach

@while ($item = array_pop($items))
    {{ $item->orSomething() }}<br>
@endwhile

@forelse ($talks as $talk)
    • {{ $talk->title }} ({{ $talk->length }} minutes)<br>
@empty
    No talks this day.
@endforelse

循环内的变量 $loop

@foreach@forelse 提供了一些原生php所没有的功能: $loop变量,在使用 @foreach@forelse 时,循环内将返回一个名叫 $loop 的标准对象,该对象具有以下属性。

  • index
    当前项目在循环中索引(位置),从 0 开始,0 代表 “第一个”

  • iteration
    当前项目在循环中索引(位置),从 1 开始,1 代表 “第一个”

  • remaining
    还剩余多少项目

  • count
    循环总数

  • first
    是否是第一项

  • last
    是否是最后一项

  • depth
    循环的层次数,1 代表 1 层循环,2 代表 2 层循环,即循环嵌套循环

  • parent
    如果此循环位于另一个循环内部,则代表对外部循环 $loop 的引用; 否则,为 null

应用如下:

<ul>
    @foreach ($pages as $page)
        <li>{{ $loop->iteration }}: {{ $page->title }}
            @if ($page->hasChildren())
                <ul>
                    @foreach ($page->children() as $child)
                        <li>{{ $loop->parent->iteration }}.{{ $loop->iteration }}:{{ $child->title }}</li>
                    @endforeach
                </ul>
            @endif
        </li>
    @endforeach
</ul>