关于lavarel:最为常用的Laravel操作3模板

3次阅读

共计 2116 个字符,预计需要花费 6 分钟才能阅读完成。

Blade 模板引擎

模板继承

定义布局:

<!-- 寄存在 resources/views/layouts/app.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>

继承布局:

<!-- 寄存在 resources/views/child.blade.php -->
@extends('layouts.app')

@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

数据显示

注:Blade 的 {{}} 语句曾经通过 PHP 的 htmlentities 函数解决以防止 XSS 攻打。

Hello, {{$name}}.

The current UNIX timestamp is {{time() }}.

输入存在的数据, 两种形式都能够:

{{isset($name) ? $name : 'Default' }}

{{$name or 'Default'}}

显示原生数据:

Hello, {!! $name !!}.

流程管制

if 语句:

@if (count($records) === 1)
    I have one record!
@elseif (count($records) > 1)
    I have multiple records!
@else
    I don't have any records!
@endif
@unless (Auth::check())
    You are not signed in.
@endunless

循环:

@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

应用循环的时候还能够完结循环或跳出以后迭代:

@foreach ($users as $user)
    @if ($user->type == 1)
        @continue
    @endif

    <li>{{$user->name}}</li>

    @if ($user->number == 5)
        @break
    @endif
@endforeach

还能够应用指令申明来引入条件:

@foreach ($users as $user)
    @continue($user->type == 1)

        <li>{{$user->name}}</li>

    @break($user->number == 5)
@endforeach

$loop 变量

在循环的时候, 能够在循环体中应用 $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 嵌套循环中的父级循环变量

模板正文

{{-- This comment will not be present in the rendered HTML --}}

嵌入 PHP 代码

@php
    //
@endphp


文章来源于自己博客,公布于 2018-06-13,原文链接:https://imlht.com/archives/156/

正文完
 0