Blade is a template engine to write the syntax easily and powerfully. To render html string in blade in laravel we use {!! $htmlstring !!}
. Using the blade template we can easily print a variable, can create loops and can create directives and components too.
Laravel blade template uses filename.blade.php
extensions and the advantages of it are so huge like we can easily include, create directive, sections, loops, conditional statements etc. in blade.
Syntax to Render Html String in Blade in Laravel
Here is the syntax of html string in blade in laravel
{!! $htmlstring !!}
here $htmlstring
variable is string which contains html like <h1> this is test </h1>
.
Let’s understand it with an example
Step 1: Create a fresh laravel project
composer create-project --prefer-dist laravel/laravel blog
Step 2: Add routes in routes/web.php
Create routes to call our controller and blade file in it.
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/test-html',function(){
$htmlstring="<h1> Test String </h1>";
$normalString = "test normal";
return view("example-view",["htmlstring"=>$htmlstring,'normalString'=>"normalString"]);
});
Step 3: Create View File
Now, create a example-view.blade.php
in resource/views
folder.
<p> this is a test </p>
html string :
{!! $htmlstring !!}
normalString :
{{ $normalString }}
How to disable html entity encoding in laravel blade ?
Laravel by default double encode html entities, sometimes we wanted to disable this feature so for this purpose we can disable it from AppServiceProvider
and we need to add Blade::withoutDoubleEncoding
method in the boot
method as below
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Blade::withoutDoubleEncoding();
}
}
Also Read : Laravel blade foreach, for and loop variable with example