💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## Blade模板 在构建视图时,不仅限于基本的PHP。你可以使用 `Laravel` 提供的强大模板引擎。我们将在以后更多地讨论和使用 Blade 模板引擎。现在,让我们利用它来创建一个布局文件,以减少页面的重复性和复杂性。 ### Blade 简介 `Blade `是 `Laravel` 提供的一个简单而又强大的模板引擎。和其他流行的 PHP 模板引擎不同,`Blade` 并不限制你在视图中使用原生 `PHP` 代码。所有 `Blade` 视图文件都将被编译成原生的 `PHP` 代码并缓存起来,除非它被修改,否则不会重新编译,这就意味着 `Blade` 基本上不会给你的应用增加任何负担。`Blade` 视图文件使用 `.blade.php` 作为文件扩展名,被存放在 `resources/views` 目录。 `Blade` 的两个主要优点是 `模板继承` 和` 区块` 。为方便入门,让我们先通过一个简单的例子来上手。 ### 定义布局 在上一节基本路由中我们创建了 `about.blade.php` 视图和 `news.blade.php` 视图,这两个视图和基本基本的 `welcome.blade.php` 视图 90% 代码重复,下面我们创建一个布局。 ``` <!-- 保存在 resources/views/layout.blade.php 文件中 --> <!doctype html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>@yield('title', 'Laravel')</title> <!-- Fonts --> <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet" type="text/css"> <!-- Styles --> <style> html, body { background-color: #fff; color: #636b6f; font-family: 'Nunito', sans-serif; font-weight: 200; height: 100vh; margin: 0; } .full-height { height: 100vh; } .flex-center { align-items: center; display: flex; justify-content: center; } .position-ref { position: relative; } .top-right { position: absolute; right: 10px; top: 18px; } .content { text-align: center; } .title { font-size: 84px; } .links > a { color: #636b6f; padding: 0 25px; font-size: 13px; font-weight: 600; letter-spacing: .1rem; text-decoration: none; text-transform: uppercase; } .m-b-md { margin-bottom: 30px; } </style> </head> <body> <div class="flex-center position-ref full-height"> <div class="content"> <div class="title m-b-md"> @yield('content') </div> <div class="links"> <a href="/">Home</a> <a href="/about">about</a> <a href="/news">News</a> </div> </div> </div> </body> </html> ``` ### 继承布局和区块 * welcome.blade.php ```php @extends('layout') @section('title', 'Laravel') @section('content') Hello Laravel @endsection ``` * about.blade.php ```php @extends('layout') @section('title', '关于我') @section('content') 假装写代码的晚黎 @endsection ``` * news.blade.php ```php @extends('layout') @section('title', 'Laravel News') @section('content') Laravel News @endsection ``` ### 总结 本节简单的介绍了 `Blade` 模板引擎的两大基本特性: `继承` 、`区块`。 `@yield` 指令在没有数据的情况下第二个参数可以指定默认值:`@yield('title', 'Laravel News')` ,同时这个指令在生成 HTML代码的时候不会产生换行。