blade template engine in laravel

 


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:

  1. 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 {{-- --}}.
  2. 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').
  3. Including Partial Views:

    • Create partial views in resources/views/includes or similar directories.
    • Include a partial view using @include('includes.header').
  4. Control Structures:

    • Use @if, @else, @elseif, and @endif for conditional statements.
    • For loops, Blade provides @for, @foreach, and @while.
  5. Escaping Content:

    • Blade automatically escapes output to prevent XSS attacks. Use {!! !!} to output unescaped data (if necessary).
  6. Blade Directives:

    • @csrf generates a hidden CSRF token field.
    • @method('PUT') or @method('DELETE') for HTML forms that use PUT or DELETE HTTP verbs.
    • @auth and @guest directives 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

Event listening in react

 How we can listen to som eevents some envents fire like click or automatically user enters into input button , that is event on word type i...