Template Syntax
Directives and escaping.
Output #
| Syntax | Description |
|---|---|
{{ $var }} |
Escaped output (XSS safe) |
{!! $var !!} |
Raw HTML output |
@{{ $var }} |
Literal {{ $var }} (escape directive) |
Directives #
Control structures #
@if($condition)
...
@elseif($other)
...
@else
...
@endif
@foreach($items as $item)
{{ $item }}
@endforeach
@for($i = 0; $i < 10; $i++)
{{ $i }}
@endfor
@while($condition)
...
@endwhile
@unless($user->isAdmin())
<p>You are not an admin.</p>
@endunless
@isset($record)
<p>Record exists.</p>
@endisset
@empty($items)
<p>No items found.</p>
@endempty
Layouts #
@extends('layouts/app')
@section('content')
<h1>{{ $title }}</h1>
@endsection
Yield with default #
@yield('sidebar', 'Default content')
Includes #
@include('partials/nav', ['active' => 'home'])
Stacks #
Push content from child views into named stacks rendered in the layout:
{{-- In layout --}}
<head>
@stack('styles')
</head>
<body>
@yield('content')
@stack('scripts')
</body>
{{-- In child view --}}
@push('styles')
<link rel="stylesheet" href="/css/page.css">
@endpush
@push('scripts')
<script src="/js/page.js"></script>
@endpush
Multiple @push calls to the same stack are concatenated in order.
Form helpers #
| Directive | Output |
|---|---|
@csrf |
Hidden CSRF token field |
@method('PUT') |
Hidden method field for form spoofing |
PHP blocks #
@php
$computed = $value * 2;
@endphp
{{ $computed }}
Safe rendering #
Use safe() on the view engine instance when rendering untrusted templates:
$engine = app('view');
$html = $engine->safe($untrustedTemplate, $data);
It disables:
- Raw output (
{!! !!}โ converted to escaped{{ }}) - PHP blocks (
@php/@endphp)
Note: In safe mode only
@if/@elseif/@else/@endifand@foreach/@endforeachdirectives are compiled. All other directives (e.g.@include,@extends,@push,@for,@while,@unless, custom directives) are silently dropped.
Custom Directives #
Register your own compile-time directives:
$engine = app('view');
$engine->directive('datetime', function (string $expression) {
return "<?php echo date('Y-m-d H:i', strtotime({$expression})); ?>";
});
Then use in templates:
@datetime($post->created_at)
The callback receives the raw expression string and must return PHP code.