0
0
Laravelframework~5 mins

Why templates separate presentation from logic in Laravel

Choose your learning style9 modes available
Introduction

Templates keep the look of a website separate from the code that makes it work. This makes it easier to change the design without breaking the code.

When you want designers to work on the website look without touching the code.
When you want to keep your code clean and easy to understand.
When you want to reuse the same design with different data.
When you want to fix bugs faster by separating concerns.
When you want to update the website style without changing the logic.
Syntax
Laravel
@extends('layout')

@section('content')
  <h1>{{ $title }}</h1>
  <p>{{ $message }}</p>
@endsection
Blade templates use {{ }} to show variables safely.
You define sections like @section('content') to fill parts of a layout.
Examples
Shows how to display variables inside HTML using Blade syntax.
Laravel
<h1>{{ $pageTitle }}</h1>
<p>Welcome, {{ $userName }}!</p>
Shows simple logic in templates to display different content.
Laravel
@if($isLoggedIn)
  <p>Hello, {{ $userName }}!</p>
@else
  <p>Please log in.</p>
@endif
Loops through data to create list items in the template.
Laravel
@foreach($items as $item)
  <li>{{ $item }}</li>
@endforeach
Sample Program

This example shows a simple Laravel route that sends data to a Blade template. The template displays the title and message inside a layout. The layout holds the common HTML structure, while the content section changes based on the page.

Laravel
<?php
// routes/web.php
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome', [
        'title' => 'Hello Laravel',
        'message' => 'Templates keep code and design separate!'
    ]);
});

// resources/views/welcome.blade.php
@extends('layout')

@section('content')
  <h1>{{ $title }}</h1>
  <p>{{ $message }}</p>
@endsection

// resources/views/layout.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My Laravel App</title>
</head>
<body>
  <header><h2>Site Header</h2></header>
  <main>
    @yield('content')
  </main>
  <footer><p>Site Footer</p></footer>
</body>
</html>
OutputSuccess
Important Notes

Templates help teams work better by letting coders and designers focus on their parts.

Blade automatically escapes variables to keep your site safe from attacks.

Keep logic simple in templates; complex code belongs in controllers or models.

Summary

Templates separate how a page looks from how it works.

This makes websites easier to build, change, and keep safe.

Laravel Blade templates use simple syntax to mix HTML and data.