> Blade 是由 Laravel 提供的非常簡單但功能強大的模板引擎
,[參考文檔](https://xueyuanjun.com/post/8773.html)
[TOC]
## Controller 中進行渲染
~~~
public function index2(RenderInterface $render)
{
$links = Link::query()->paginate(10);
return $render->render('index.index', ['links' => $links]);
}
~~~
## 注釋
> 不同于 HTML 注釋,Blade 注釋并不會包含到 HTML 中被返回
~~~
{{-- This comment will not be present in the rendered HTML --}}
~~~
## 插槽輸出
> 為了避免 XSS 攻擊,會自動對數據進行轉義
> 插槽里可以調用任何方法,進行返回值的顯示
~~~
{{ $name }}
~~~
## 原生數據顯示
~~~
{!! $content !!}
~~~
## 渲染 JSON 內容
> 有時候你可能會將數據以數組方式傳遞到視圖再將其轉化為 JSON 格式以便初始化某個 JavaScript 變量
~~~
<script>
var app = <?php echo json_encode($array); ?>;
</script>
~~~
> 推薦使用Blade 的 @json 指令
~~~
<script>
var app = @json($array);
</script>
~~~
## If 語句
> 可以使用 @if , @elseif , @else 和 @endif 來構造 if 語句,這些指令的功能和 PHP 相同
~~~
@if (count($records) === 1)
I have one record!
@elseif (count($records) > 1)
I have multiple records!
@else
I don't have any records!
@endif
~~~
## 循環
~~~
@for ($i = 0; $i < 10; $i++)
The current value is {{ $i }}
@endfor
@foreach ($users as $user)
@if ($user->type == 1)
@continue
@endif
<li>{{ $user->name }}</li>
@if ($user->number == 5)
@break
@endif
@endforeach
~~~
### $loop變量
~~~
@foreach ($users as $user)
@if ($loop->first)
This is the first iteration.
@endif
@if ($loop->last)
This is the last iteration.
@endif
<p>This is user {{ $user->id }}</p>
@endforeach
~~~
> 如果你身處嵌套循環,可以通過 $loop 變量的 parent 屬性訪問父級循環
~~~
@foreach ($users as $user)
@foreach ($user->posts as $post)
@if ($loop->parent->first)
This is first iteration of the parent loop.
@endif
@endforeach
@endforeach
~~~
> $loop 變量還提供了其他一些有用的屬性
| 屬性 | 描述 |
| --- | --- |
| `$loop->index` | 當前循環迭代索引 (從0開始) |
| `$loop->iteration` | 當前循環迭代 (從1開始) |
| `$loop->remaining` | 當前循環剩余的迭代 |
| `$loop->count` | 迭代數組元素的總數量 |
| `$loop->first` | 是否是當前循環的第一個迭代 |
| `$loop->last` | 是否是當前循環的最后一個迭代 |
| `$loop->depth` | 當前循環的嵌套層級 |
| `$loop->parent` | 嵌套循環中的父級循環變量 |