0
0
LaravelHow-ToBeginner · 3 min read

How to Use {{ }} in Blade Templates in Laravel

In Laravel Blade templates, use {{ }} to display variables or expressions safely by escaping HTML. This syntax outputs the value of the variable inside the braces directly into the HTML view.
📐

Syntax

The {{ }} syntax in Blade is used to output variables or expressions. Anything inside the braces is evaluated and displayed as HTML-escaped text to prevent security issues like cross-site scripting (XSS).

For example, {{ $name }} will print the value of the $name variable.

blade
<p>{{ variable_or_expression }}</p>
Output
<p>value_of_variable_or_expression</p>
💻

Example

This example shows how to use {{ }} to display a variable in a Blade template safely.

blade
@php
  $name = 'Alice';
@endphp

<h1>Hello, {{ $name }}!</h1>
Output
<h1>Hello, Alice!</h1>
⚠️

Common Pitfalls

One common mistake is trying to output raw HTML using {{ }}, which escapes HTML tags and shows them as plain text. To output raw HTML, use {!! !!} instead.

Another pitfall is forgetting to pass the variable from the controller to the view, which results in an undefined variable error.

blade
@php
  $html = '<strong>Bold Text</strong>';
@endphp

<!-- Wrong: HTML tags will be escaped -->
<p>{{ $html }}</p>

<!-- Right: HTML tags will render -->
<p>{!! $html !!}</p>
Output
<p>&lt;strong&gt;Bold Text&lt;/strong&gt;</p> <p><strong>Bold Text</strong></p>
📊

Quick Reference

SyntaxDescription
{{ $variable }}Outputs escaped variable content safely
{!! $variable !!}Outputs raw HTML without escaping
@php ... @endphpEmbed PHP code inside Blade
{{-- comment --}}Blade comment, not rendered in HTML

Key Takeaways

Use {{ }} in Blade to safely display variables with HTML escaping.
To output raw HTML, use {!! !!} instead of {{ }}.
Always pass variables from your controller to the Blade view.
{{ }} helps prevent security issues like cross-site scripting.
Blade syntax is simple and designed for clean, readable templates.