
{{ $('Map tags to IDs').item.json.title }}
How to Use Blade Templates in Laravel
Blade is the powerful templating engine provided with Laravel, allowing you to create dynamic views for your web applications. Blade provides a straightforward and expressive syntax that enables developers to combine PHP with HTML seamlessly. This tutorial will guide you through using Blade templates effectively.
Prerequisites
- Basic understanding of PHP and Laravel.
- A Laravel project set up and running.
1. Working with Blade Templates
Blade templates use the .blade.php
file extension and are stored in the resources/views
directory. When you create a new view file, ensure it ends with .blade.php
.
1.1. Creating a Blade Template
Create a new Blade template by creating a file called example.blade.php
in the resources/views
directory:
touch resources/views/example.blade.php
Add the following HTML and Blade syntax:
<!DOCTYPE html>
<html>
<head>
<title>Blade Template Example</title>
</head>
<body>
<h1>Welcome to Blade Templates!</h1>
<p>Today is: {{ date('Y-m-d') }}</p>
</body>
</html>
2. Rendering a Blade Template
To render the Blade template, create a route in your routes/web.php
file:
Route::get('/example', function () {
return view('example');
});
When you navigate to http://your-app-url/example
, Laravel will render the example.blade.php
template.
3. Blade Template Syntax
Blade provides several features to simplify common tasks:
- Variables: Use
{{ variable }}
to output data directly in your templates. - Control Structures: You can use if statements or loops:
<?php $items = ['Item 1', 'Item 2', 'Item 3']; ?>
<ul>
@foreach ($items as $item)
<li>{{ $item }}</li>
@endforeach
</ul>
@* This is a comment *@
4. Extending Blade Layouts
Blade allows you to create layout templates for a consistent look and feel. Create a layout file called layouts/app.blade.php
:
<!DOCTYPE html>
<html>
<head>
<title>@yield('title')</title>
</head>
<body>
<div class="container">
@yield('content')
</div>
</body>
</html>
In your example.blade.php
, you can extend this layout:
@extends('layouts.app')
@section('title', 'Blade Template Example')
@section('content')
<h1>Welcome to Blade Templates!</h1>
<p>Today is: {{ date('Y-m-d') }}</p>
@endsection
5. Conclusion
By following this tutorial, you have learned the basics of using Blade templates in Laravel applications. Blade offers a powerful syntax that enhances the development experience, making it easier to manage your application’s views. Explore further features of Blade to take full advantage of this templating engine in your projects!