Blade 模板引擎

2021/9/25 23:13:35

本文主要是介绍Blade 模板引擎,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1,Blade 模板引擎有三种常见的语法:

  • 通过 {{ }} 渲染 PHP 变量(最常用)
  • 通过 {!! !!} 渲染原生 HTML 代码(用于富文本数据渲染)
  • 通过以 @ 作为前缀的 Blade 指令执行一些控制结构和继承、引入之类的操作

<h1>{{ $name }}</h1> 
{!!  html !!} 
@ if($users==1) 
   代码
@endif

@empty 
    该组中没有任何用户 
@endempty

2,Blade 模板代码存放在以 .blade.php 后缀结尾的视图文件中,最终会被编译为原生 PHP 代码,并缓存起来,直到视图模板有修改才会再次编译,所以拥有与原生 PHP 几乎一致的性能。可以在 Blade 模板中使用原生 PHP 代码。

3,通过{{$name}} 等价于 <?php echo htmlentities($name);?>

{{ isset($name) ? $name : 'Default' }}等价于{{ $name or 'Default' }}

4, {{-- 注释内容 --}}

5,html页面中的js渲染,使用@{{$vuedata}}

// Blade 引擎会将其编译为对应的 PHP 代码
{{ $phpData }}
// Blade 引擎编译时会移除 @,保留 {{ $vueData }} 结构
@{{ $vueData }}

6,控制语句

@if (count($students) === 1) 
    操场上只有一个同学
@elseif (count($students) === 0)
    操场上一个同学也没有
@else
    操场上有 {{ count($students) }} 个同学
@endif

@unless ($user->hasPaid()) 
    用户支付之后才能享受该服务
@endunless


@isset($records)
    // 记录被设置
@endisset

@empty($records)
    // 记录为空
@endempty


@switch($i)
    @case(1)
        // $i = 1 做什么
        @break

    @case(2)
        // $i = 2 做什么
        @break

    @default
        // 默认情况下做什么
@endswitch



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

// foreach 循环
@foreach ($talks as $talk)
    {{ $talk->title }} ({{ $talk->length }} 分钟)<br> 
@endforeach

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


@forelse ($students as $student)
    // do something ...
@empty
    // do something else ...
@endforelse  



<ul> 
@foreach ($pages as $page)
    @if ($loop->first)
        // 第一个循环迭代
    @endif 
    <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> 
    @if ($loop->last)
        // 最后一个循环迭代
    @endif
@endforeach 
</ul>

7,通过@include 引入组件

<!-- resources/views/sign-up-button.blade.php --> 
<a class="button button--callout" data-page-name="{{ $pageName }}">
    <i class="exclamation-icon"></i> {{ $text }} 
</a>


-----------------------------------------------

<!-- resources/views/home.blade.php --> 
<div class="content" data-page-name="{{ $pageName }}">
    <p>为什么要注册 Laravel 学院: <strong>能提供更多服务</strong></p>
    @include('sign-up-button', ['text' => '看看到底有哪些服务']) 
</div> 

8,@extends 指令来明确的指定继承某个布局,@section 指令就如它的名字所暗示的那样定义了一个内容区块,而 @yield 指令是用来显示所提供的挂件区块所包含的内容。 

9,堆,使用push压入内容,使用 @stack 来渲染堆

@push('scripts')
  <script src="/example.js"></script>
@endpush

使用

<head>
  <!-- Head Contents -->

  @stack('scripts')
</head>

 



这篇关于Blade 模板引擎的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程