In Laravel, the default template engine is Blade, which is a powerful and intuitive engine for writing PHP-based templates. Here's a quick overview of Blade and how to use it:
Blade Syntax Basics:
- Blade uses curly braces (
{{ }}) to echo variables:{{ $variable }}. - You can use
@to execute PHP code inside Blade templates:@if,@foreach,@extends, etc. - Blade comments use
{{-- --}}.
- Blade uses curly braces (
Extending Layouts:
- Create a master layout in
resources/views/layouts/app.blade.php. - Use
@yield('content')in the layout file where you want child views to be inserted. - Extend the layout in a child view with
@extends('layouts.app')and define content using@section('content').
- Create a master layout in
Including Partial Views:
- Create partial views in
resources/views/includesor similar directories. - Include a partial view using
@include('includes.header').
- Create partial views in
Control Structures:
- Use
@if,@else,@elseif, and@endiffor conditional statements. - For loops, Blade provides
@for,@foreach, and@while.
- Use
Escaping Content:
- Blade automatically escapes output to prevent XSS attacks. Use
{!! !!}to output unescaped data (if necessary).
- Blade automatically escapes output to prevent XSS attacks. Use
Blade Directives:
@csrfgenerates a hidden CSRF token field.@method('PUT')or@method('DELETE')for HTML forms that use PUT or DELETE HTTP verbs.@authand@guestdirectives for checking authentication status.
Here's an example of a Blade template:
php@extends('layouts.app')
@section('content')
<div class="container">
@if($user)
<h1>Welcome, {{ $user->name }}</h1>
@else
<h1>Welcome, Guest</h1>
@endif
@foreach($posts as $post)
<div class="post">
<h2>{{ $post->title }}</h2>
<p>{{ $post->content }}</p>
</div>
@endforeach
</div>
@endsection
In this example, @extends('layouts.app') extends the app.blade.php layout, and @section('content') defines the content section of the page. Inside, we have conditional statements (@if, @else) and a loop (@foreach) to display data dynamically.
No comments:
Post a Comment