Laravel Escaping All HTML in Blade Template
I’m building a small CMS in Laravel and I tried to show the content (which is stored in the DB). It is showing the HTML tags instead of executing them. Its like there is an auto html_entity_decode for all printed data.
where('page_name', '=', $name) ->first(); return View::make('cms.page')->with('content', $data); > >
Are they stored as «tags» or already escaped in the db? Because else I would see it like The Alpha, this should only be the case in v5 of laravel
7 Answers 7
Change your syntax from > to .
As The Alpha said in a comment above (not an answer so I thought I’d post), in Laravel 5, the > (previously non-escaped output syntax) has changed to . Replace > with and it should work.
@IvanTopolcic is there a way to extract the html coming back from an @yield(‘content’) blade directive?
This answer worked for my in Laravel 5.2. In the course of working on the problem, I also discovered that Illuminate/Support/helpers.php::529 runs htmlentities() if you don’t use this syntax: .!!>
I had the same issue. Thanks for the answers above, I solved my issue. If there are people facing the same problem, here is two way to solve it:
There is no problem with displaying HTML code in blade templates.
For test, you can add to routes.php only one route:
Route::get('/', function () < $data = new stdClass(); $data->page_desc = 'aaabbb New paragaph
'; return View::make('hello')->with('content', $data); > );
and in hello.blade.php file:
For the following code you will get output as on image
So probably page_desc in your case is not what you expect. But as you see it can be potential dangerous if someone uses for example ‘` tag so you should probably in your route before assigning to blade template filter some tags
I’ve also tested it with putting the same code into database:
Route::get('/', function () < $data = User::where('id','=',1)->first(); return View::make('hello')->with('content', $data); > );
Output is exactly the same in this case
I also don’t know if Pages is your model or it’s a vendor model. For example it can have accessor inside:
public function getPageDescAttribute($value)
and then when you get page_desc attribute you will get modified page_desc with htmlspecialchars . So if you are sure that data in database is with raw html (not escaped) you should look at this Pages class
Laravel Render Html in Controller 5 different ways
Laravel Render Html in Controller could be confusing for beginners.
In this tutorial, I will show you how to pass HTML element from laravel controller to view. At the end of the tutorial, you will also learn how to return a view from controller to laravel blade .
Before you do any coding make sure that, you are naming your view files with .blade.php suffix and they are saved in resources/views folder
1. Using double curly braces
If your controller passes a string variable to laravel blade,
$str="This is my html render";
and if you want to display text or paragraphs which is passed from the controller, you should do like this
Within double curly braces , you should write your variable that is passed from controller to blade, and you are good to go and you will see
This is the most common way laravel render html if you don’t have any tags.
For explanation, the above statement is the same as the line below. PHP auto inverts from > to
Here e() is convenience wrapper for echo() function. But it’s already deprecated in Laravel.
Build a complete mobile app with Laravel Backend
2. Using single curly braces and exclamation marks
Say, you have a variable $str in controller with some html tag like the below one and you want to send to blade using compact() function in laravel.
After receiving on the blade, variable $str contains HTML tag. Then you must use a single curly brace in each side and double exclamation marks on both side of the variable, and this is the most common ways of laravel not escaping HTML in the blade template
And then your output would be like below. Remember you use single curly braces and two exclamation marks to display your variable value.
√ So > curly braces print the string as it is, but will render HTML from a string variable. And laravel blade double exclamation should be used when you have HTML tags in your string.
The above one is really useful when you want to render HTML from database to view blade.
3. Using html_entity_decode() function
This is our good old PHP function which does a lot of work for you. This function removes HTML entities from a string, what is HTML entities? They are special strings that starts with &(ampersend) sign and ends with ;(semicolon). See the below code which contains a few HTML entities.
In the above function $str contains HTML entities and variable $str after being passed through html_entity_decode() function in blade,
it produces the output like below
So next time if you have string that contains HTML entities, just use this HTML entity decode function and your problems would be solved.
You can also use when you want laravel to render HTML from database .
You use html_entity_decode in laravel if
√ You want to render HTML from database
√ If your string has HTML entities
4. Use traditional PHP opening
You can render HTML in blade using traditional PHP opening and closing tag. You can write
In your blade. The variable $string is coming from your controller. But it’s not recommended to do like this. This is more like spaghetti code, where you put PHP and HTML together.
5. Use Laravel PHP directive
Laravel is famous for it’s clean and readable PHP syntax. If the method mentioned in 4, looks like a spaghetti code for you then try the below one
It’s one of my favorite way of writing PHP in Laravel blade.
Things to remember about laravel blade escape html
√ If you want to render a string and it does not contain any special characters or html tags then use >
√ If your variable string includes html tags but not any html entities then just use for unescaping HTML. Becuase > escape HTML tags meaning that, > will ecapse html.
√ If you variable contains both html tags and html entities then use
√ If you render any string that is coming from the database.
Laravel return HTML from controller
In general, we don’t return an entire view from laravel controller. Even if you want to do it, you can. Let’s see how to return entire HTML document strings from controller.
$str= ' We love laravel. Its the best web framework
The Best Technology '; return view('greeting', compact('str'));
After laravel return HTML in controller, the blade should be like below code sinppet
Build a complete backend of Laravel
Build a mobile app with Laravel Backend
Displaying HTML with Blade shows the HTML code
However, the output is a raw string instead of rendered HTML. How do I display HTML with Blade in Laravel? PS. PHP echo() displays the HTML correctly.
@MuhammadShahzad answer works well. Tested on Laravel 9 after searching for a solution for a while. Thank you.
20 Answers 20
The string will auto escape when using > .
Here are the Laravel docs that mention this: «If you do not want your data to be escaped, you may use the following syntax: Hello, . » laravel.com/docs/5.5/blade#displaying-data !!>
@sanders It quite likely is a security issue if $text contains user input and you did not escape this properly. For example, $text = ‘Hello ‘.$_GET[‘name’].’‘; is dangerous because $_GET[‘name’] could include HTML, which would allow XSS. You could do $text = ‘Hello ‘.htmlentities($_GET[‘name’]).’‘; and would be safe.
this dose not do the whole trick! if I had something like and I wanna show it in blade, It will look like this . So the answer for me is @Praveen_Dabral ‘s
Figured out through this link, see RachidLaasri answer
This provides exactly the same result as the accepted answer, for the data given in the question. The only case where it would behave differently is if there were HTML entities in $text .
Only in case of HTML while if you want to render data, sting etc. use
This is because when your blade file is compiled
There is another way. If object purpose is to render html you can implement \Illuminate\Contracts\Support\Htmlable contract that has toHtml() method.
Then you can render that object from blade like this: > (note, no need for syntax).
Also if you want to return html property and you know it will be html, use \Illuminate\Support\HtmlString class like this:
public function getProductDescription() < return new HtmlString($this->description); >
and then use it like getProductDescription() >> .
Of course be responsible when directly rendering raw html on page.
Returning HTML from a Form field Macro, this is exactly the right solution. Return the HTML string from the function, using this method, and call the Macro within your Blade template. +1
When your data contains HTML tags then use
When your data doesn’t contain HTML tags then use
Try this. It worked for me.
In Laravel Blade template, > wil escape html. If you want to display html from controller in view, decode html from string.
You can do that using three ways first use if condition like below
@if( $order->status == '0' ) @else @endif
The third and proper way for use ternary operator on blade
status=='0' ? ' : ' !!>
I hope the third way is perfect for used ternary operator on blade.
you can do with many ways in laravel 5..
To add further explanation, code inside Blade > statements are automatically passed through the htmlspecialchars() function that php provides. This function takes in a string and will find all reserved characters that HTML uses. Reserved characters are & < >and » . It will then replace these reserved characters with their HTML entity variant. Which are the following:
For example, assume we have the following php statement:
Passed into blade as > would yield the literal string you passed:
Under the hood, it would actually echo as <b>Hello<b>
If we wanted to bypass this and actually render it as a bold tag, we escape the htmlspecialchars() function by adding the escape syntax blade provides:
Note that we only use one curly brace.
The output of the above would yield:
We could also utilise another handy function that php provides, which is the html_entity_decode() function. This will convert HTML entities to their respected HTML characters. Think of it as the reverse of htmlspecialchars()
For example say we have the following php statement:
We could now add this function to our escaped blade statement:
This will take the HTML entity < and parse it as HTML code < , not just a string.
The same will apply with the greater than entity >
The whole point of escaping in the first place is to avoid XSS attacks. So be very careful when using escape syntax, especially if users in your application are providing the HTML themselves, they could inject their own code as they please.
Laravel 5: отображение HTML с помощью Blade
Однако вывод представляет собой необработанную строку вместо отображаемого HTML. Как отобразить HTML с Blade в Laravel 5? PS. PHP echo() отображает HTML правильно.
18 ответов
Вот документы Laravel, в которых упоминается это: «Если вы не хотите, чтобы ваши данные были экранированы, вы можете использовать следующий синтаксис: Hello, . » Laravel.com/docs/5.5/blade# отображение данных, !!>
@sanders Скорее всего, это проблема безопасности, если $text содержит пользовательский ввод, и вы не избежали этого должным образом. Например, $text = ‘Hello ‘.$_GET[‘name’].’‘; опасно, потому что $_GET[‘name’] может включать HTML, что позволит использовать XSS. Вы можете сделать $text = ‘Hello ‘.htmlentities($_GET[‘name’]).’‘; и будет в безопасности.
эта доза не сделает весь трюк! если у меня было что-то вроде и я хочу показать это в клинке, это будет выглядеть так . Так что ответ для меня — @Praveen_Dabral’s
Выявлено это ссылка, см. ответ RachidLaasri
Вы можете попробовать это:
Только в случае HTML, в то время как если вы хотите визуализировать данные, используйте sting и т.д.
Это потому, что когда ваш блейд файл скомпилирован
Попробуйте это. Это сработало для меня.
В шаблоне Blade Laravel, > wil escape html. Если вы хотите отобразить html из контроллера в поле зрения, декодируйте html из строки.
это не правильно, это выше ответов, это может быть сделано по-вашему, это просто сбивает с толку программиста
Есть и другой способ. Если целью объекта является рендеринг html, вы можете реализовать контракт \Illuminate\Contracts\Support\Htmlable , который имеет метод toHtml() .
Затем вы можете визуализировать этот объект из лезвия следующим образом: > (обратите внимание, нет необходимости в синтаксисе ).
Также, если вы хотите вернуть свойство html, и знаете, что это будет html, используйте класс \Illuminate\Support\HtmlString следующим образом:
public function getProductDescription() < return new HtmlString($this->description); >
а затем используйте его как getProductDescription() >> .
Конечно, ответьте, когда напрямую передаете raw html на странице.