Laravel 5.1
Session 04
Muhammad Rizwan Arshad,
Principal Software Engineer, Nextbridge.
July 30, 2015.
Views
Basic Usage
View stored in resources/views/greeting.php
<html>
<body>
<h1>Hello, <?php echo $name; ?></h1>
</body>
</html>
Route::get('/', function () {
return view('greeting', ['name' => 'James']);
});
Nested within sub-directories
return view('admin.profile', $data);
Determining If A View Exists
if (view()->exists('emails.customer')) {
//
}
Passing Data To Views
return view('greetings', ['name' => 'Victoria']);
$view = view('greeting')->with('name', 'Victoria');
Blade Templates
Defining A Layout
<!-- 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>
Extending A Layout
<!-- 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
Displaying Data
Route::get('greeting', function () {
return view('welcome', ['name' => 'Samantha']);
});
Hello, {{ $name }}.
The current UNIX timestamp is {{ time() }}.
Blade {{ }} statements are automatically sent through PHP's htmlentities function to prevent XSS attacks.
Blade & JavaScript Frameworks
<h1>Laravel</h1> Hello, @{{ name }}. In this example, the @ symbol will be removed by Blade; However, {{ name }} expression will remain untouched by the Blade engine
Echoing Data If It Exists
{{ isset($name) ? $name : 'Default' }} {{ $name or 'Default' }}
Displaying Unescaped Data
Hello, {!! $name !!}.
Be very careful when echoing content that is supplied by users of your application. Always use the double curly brace syntax to escape any HTML entities in the content.
Control Structures
If Statements
@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
Loops
@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
Including Sub-Views
<div> @include('shared.errors') <form> <!-- Form Contents --> </form> </div>
@include('view.name', ['some' => 'data'])
Comments
{{-- This comment will not be present in the rendered HTML --}}
That's all for today!
Laravel 5.1 Session 04 Muhammad Rizwan Arshad, Principal Software Engineer, Nextbridge. July 30, 2015.
Laravel 5.1 - Session 04
By gr8rizwan
Laravel 5.1 - Session 04
- 1,132