Laravel5.1学习笔记8 Blade模板
简介
Blade 是 Laravel 提供的一个既简单又强大的模板引擎。和其他流行的 PHP 模板引擎不一样,Blade 并不限制你在视图(view)中使用原生 PHP 代码。所有 Blade 视图页面都将被编译成原生 PHP 代码并缓存起来,除非你的模板文件被修改了,否则不会重新编译,这就意味着 Blade 基本上不会给你的应用增加任何额外负担。Blade 视图文件使用 .blade.php 文件扩展名,并且一般被存放在resources/views 目录。
模板继承
定义一个页面布局模板
使用 Blade 能获得的两个主要好处是 模板继承(template inheritance) 和 视图片断(sections)。我们先通过一个简单的实例认识一下 Blade 模板吧。首先,我们先来看一下命名为 "master" 的页面布局模板。由于大部分网站应用都会在页面之间共享某些相同的布局,所以将这个页面布局定义在一个单独的 Blade 模板中更便于使用。
<!-- Stored in resources/views/layouts/master.blade.php --> <html>
<head>
<title>App Name - @yield('title')</title>
</head>
<body>
@section('sidebar')
This is the master sidebar.
@show <div class="container">
@yield('content')
</div>
</body>
</html>
如上所见,这个文件中包含了通常见到的 HTML 标签。不过,请注意一下 @section 和 @yield 指令。@section 指令正像其名字所暗示的一样是用来定义一个视图片断(section)的;@yield 指令是用来展示某个指定 section 所代表的内容的。
好了,我们已经定义了一个页面布局模板了,接下来我们定义一个继承页面布局模板的子页面模板。
扩展一个页面布局模板
定义子页面时,你需要使用 Blade 提供的 @extends 指令来为子页面指定其所“继承”的页面布局模板。Views which @extends a Blade layout may inject content into the layout's sections using@section directives. Remember, as seen in the example above, the contents of these sections will be displayed in the layout using @yield:
<!-- Stored in resources/views/layouts/child.blade.php -->
@extends('layouts.master')
@section('title', 'Page Title')
@section('sidebar')
@@parent
<p>This is appended to the master sidebar.</p>
@endsection
@section('content')
<p>This is my body content.</p>
@endsection
在上面的实例中,sidebar section is utilizing the @@parent directive to append (rather than overwriting) content to the layout's sidebar. The @@parent directive will be replaced by the content of the layout when the view is rendered.
Of course, just like plain PHP views, Blade views may be returned from routes using the global view helper function:
Route::get('blade', function () {
return view('child');
});
展示数据
You may display data passed to your Blade views by wrapping the variable in "curly" braces. For example, given the following route:
Route::get('greeting', function () {
return view('welcome', ['name' => 'Samantha']);
});
你可以像下面这样展示 name 变量所代表的内容:
Hello, {{ $name }}.
当然,你不仅仅被局限于展示传递给视图的变量,你还可以展示 PHP 函数的返回值。事实上,你可以在 Blade 模板的双花括号表达式中调用任何 PHP 代码:
The current UNIX timestamp is {{ time() }}.
注意: Blade 中的
{{ }}表达式的返回值将被自动传递给 PHP 的htmlentities函数进行处理,以防止 XSS 攻击。
Blade & JavaScript 框架
由于很多 JavaScript 框架也使用 "花括号" 来表示一个需要在浏览器端解析的表达式,因此,你可以通过使用 @ 符号来告知 Blade 模板引擎保持后面的表达式原样输出。如下所示:
<h1>Laravel</h1>
Hello, @{{ name }}.
在上述实例中,@ 符号将被 Blade 移除,同时,{{ name }} 表达式将被原样输出,这就能够确保在浏览器端被你的 JavaScript 框架解释了。
如果数据存储就将其输出
某些时候你需要输出变量的值,但是在输出前你并不知道这个变量是否被赋值了。我们将这个问题化作代码描述如下:
{{ isset($name) ? $name : 'Default' }}
不过,上面的表达式的确很繁复,幸好 Blade 提供了如下的速记方式:
{{ $name or 'Default' }}
在这个实例中,如果 $name 变量被赋了值,它的值将被输出出来。然而,如果没有被赋值,将输出默认的单词 Default 。
展示未转义的数据
默认情况下,Blade 的 {{ }} 表达式会自动通过 PHP 的 htmlentities 函数进行处理,以防止 XSS 攻击。如果你不希望自己的数据被转义,请使用如下语法:
Hello, {!! $name !!}.
注意: 务必要对用户上传的数据小心处理。最好对内容中的所有 HTML 使用双花括号进行输出,这样就能转义内容中的任何 HTML 标签了。
#Control Structures (控制逻辑)
In addition to template inheritance and displaying data, Blade also provides convenient short-cuts for common PHP control structures, such as conditional statements and loops. These short-cuts provide a very clean, terse way of working with PHP control structures, while also remaining familiar to their PHP counterparts.
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
为了使用方面,Blade 还提供了 @unless 指令:
@unless (Auth::check())
You are not signed in.
@endunless
循环
除了状态表达式,Blade 还提供了简单的循环指令,与 PHP 所支持的循环结构相一致。并且,每一个指令的功能都和相对应的 PHP 表达式是一致的。
@for ($i = 0; $i < 10; $i++)
The current value is {{ $i }}
@endfor @foreach ($users as $user)
<p>This is user {{ $user->id }}</p>
@endforeach @forelse ($users as $user)
<li>{{ $user->name }}</li>
@empty
<p>No users</p>
@endforelse @while (true)
<p>I'm looping forever.</p>
@endwhile
引入子视图
Blade 提供的 @include 指令允许你方便地在一个视图中引入另一个视图。所有父视图中可用的变量也都可以在被引入的子视图中使用。
<div>
@include('shared.errors') <form>
<!-- Form Contents -->
</form>
</div>
虽然被引入的子视图能够访问父视图的所有可用数据,但是,你还可以向被引入的子视图传递额外的数据:
@include('view.name', ['some' => 'data'])
注释
Blade 还允许你在视图中添加注释。然而,和 HTML 注释不同的是,Blade 注释不会出现在最终生成的 HTML 中。
{{-- This comment will not be present in the rendered HTML --}}
#Service Injection
The @inject directive may be used to retrieve a service from the Laravel service container. The first argument passed to @inject is the name of the variable the service will be placed into, while the second argument is the class / interface name of the service you wish to resolve:
@inject('metrics', 'App\Services\MetricsService')
<div>
Monthly Revenue: {{ $metrics->monthlyRevenue() }}.
</div>
#扩展 Blade
Blade even allows you to define your own custom directives. You can use the directivemethod to register a directive. When the Blade compiler encounters the directive, it calls the provided callback with its parameter.
下面这个实例将创建一个 @datetime($var) 指令,用于格式化 $var 参数:
<?php namespace App\Providers; use Blade;
use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider
{
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
Blade::directive('datetime', function($expression) {
return "<?php echo with{$expression}->format('m/d/Y H:i'); ?>";
});
} /**
* Register bindings in the container.
*
* @return void
*/
public function register()
{
//
}
}
As you can see, Laravel's with helper function was used in this directive. The with helper simply returns the object / value it is given, allowing for convenient method chaining. The final PHP generated by this directive will be:
<?php echo with($var)->format('m/d/Y H:i'); ?>
Laravel5.1学习笔记8 Blade模板的更多相关文章
- 微信小程序开发:学习笔记[2]——WXML模板
微信小程序开发:学习笔记[2]——WXML模板 快速开始 介绍 WXML 全称是 WeiXin Markup Language,是小程序框架设计的一套标签语言,结合小程序的基础组件.事件系统,可以构建 ...
- laravel5.1框架基础之Blade模板继承简单使用方法分析
本文实例讲述了laravel5.1框架基础之Blade模板继承简单使用方法.分享给大家供大家参考,具体如下: 模板继承什么用? 自然是增强基础页面的复用,有利于页面文档的条理,也便于更改多处使用的内容 ...
- laravel5.4学习笔记
1.安装laravel可以直接用composer安装,然后用laravel new xxx来新建项目 服务器上安装了composer(php包管理工具)以后, composer global requ ...
- Laravel5.1学习笔记10 系统架构2 应用程序结构
应用程序结构 简介 根目录 App 目录 为应用程序设置命名空间 简介 默认的 Laravel 应用程序结构是为了给无论构建大型还是小型应用程序都提供一个良好的开始.当然,你可以依照喜好自由地组织应用 ...
- Laravel5.1学习笔记5 请求
HTTP 请求 #取得请求实例 #基本的请求信息 #PSR-7 请求 #取出输入数据 #旧的输入 #Cookies #文件 #取得请求实例(此部分文档5.1完全重写,注意) 要通过依赖注入获取当前HT ...
- Laravel5.1 学习笔记2, 路由
安装的说明请看文档, laravel 安装 #基本路由 你将在 app/Http/routes.php 文件定义大部分路由, 这些路由将被App\Providers\RouteServiceProvi ...
- AMQ学习笔记 - 05. 客户端模板化
概述 客户端编程模型中,大部分的步骤都是相同的.将相同的部分做成模板,将不同的部分预留接口,实现者就只需要针对不同的部分提供实现. 设计 类图 发送方客户端 说明: 基于模板的思想,SendTempl ...
- AngularJS1.X学习笔记3-内置模板指令
前面学习了数据绑定指令,现在开始学习内置模板指令.看起来有点多,目测比较好理解.OK!开始! 一.ng-repeat 1.基本用法 <!DOCTYPE html> <html lan ...
- 最近公共祖先(LCA)学习笔记 | P3379 【模板】最近公共祖先(LCA)题解
研究了LCA,写篇笔记记录一下. 讲解使用例题 P3379 [模板]最近公共祖先(LCA). 什么是LCA 最近公共祖先简称 LCA(Lowest Common Ancestor).两个节点的最近公共 ...
随机推荐
- [系统资源攻略]CPU使用率和负载
我们在搞性能测试的时候,对后台服务器的CPU利用率监控是一个常用的手段.服务器的CPU利用率高,则表明服务器很繁忙.如果前台响应时间越来越大,而后台CPU利用率始终上不去,说明在某个地方有瓶颈了,系统 ...
- 一个电商项目的Web服务化改造7:Dubbo服务的调用,4个项目
使用dubbo服务的过程,很简单,和之前学习的WebService完全一样,和本地接口调用也基本一致. dubbo和WebService的区别:我认为dubbo就是封装了WebService,然后提供 ...
- PKI 的组成
PKI(Public Key Infrastructure)公钥基础设施是提供公钥加密和数字签名服务的系统或平台,目的是为了管理密钥和证书.一个机构通过采用PKI 框架管理密钥和证书可以建立一个安全的 ...
- 【Codeforces 478C】Table Decorations
[链接] 我是链接,点我呀:) [题意] 给你r,g,b三种颜色的气球 每张桌子要放3个气球 但是3个气球的颜色不能全都一样 (允许两个一样,或者全都不一样) 问你最多能装饰多少张桌子 [题解] 先把 ...
- Python之路【第一篇】:Python基础
本节内容 Python介绍 发展史 Python 2 or 3? 安装 Hello World程序 变量 用户输入 模块初识 .pyc是个什么鬼? 数据类型初识 数据运算 表达式if ...else语 ...
- hdu_1036_Average is not Fast Enough_201311021335
Average is not Fast Enough! Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (J ...
- 机器学习10k均值
下面介绍无监督机器学习算法,与前面分类回归不一样的是,这个不知道目标变量是什么,这个问题解决的是我们从这些样本中,我们能发现什么. 这下面主要讲述了聚类算法,跟数据挖掘中的关联挖掘中的两个主要算法. ...
- Hard模式题目
先过一下Hard模式的题目吧. # Title Editorial Acceptance Difficulty Frequency . 65 Valid Number 12.6% Ha ...
- HDU 5293
树上DP题. 其实有点类似于01的问题.方程很容易想到.首先,因为一条链的节点其实都是在树上的,所以很容易想到应该先求一个LCA.然后,当某节点不是链的LCA时,它的转移就是: dp[i]=sum[i ...
- maven的启动类和MAVEN_OPTS参数
maven的启动类和MAVEN_OPTS参数 在mvn.cmd的155行, set CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launc ...