Displaying HTML with Blade shows the HTML code
You need to use
{!! $text !!}
The string will auto escape when using {{ $text }}
.
How to render html in laravel blade
you can use this {!! $text !!} to render html
how to display html values from a database in a blade view in Laravel?
You need to unescape the element in blade.
Instead of:
{{ $element }}
Use:
{!! $element !!}
As Lagbox notes in the comments, it is important that if you use unescaped data, that you have purified it in advance.
why the html code sent by controller displays in my page?
If you want to display the complied html you can use the below syntax and docs can be found Here
<div>{!! $stockLevel !!}</div>
Or You can use HtmlString
class
<div>{{new Illuminate\Support\HtmlString($stockLevel )}}</div>
and be careful with XSS vulnerability
Or you can pass data from Controller
public function show($id)
{
$stockLevelStatus = $stockLevelBadge = null;
$annonces = Annonce::where('id', $id)->firstOrfail();
$mightAlsoLike = Annonce::where('id', '!=', $id)->mightAlsoLike()->get();
if ($annonces->quantity > setting('site.stock_threshold')) {
$stockLevelStatus = 'In Stock';
$stockLevelBadge = 'badge-success';
} elseif ($annonces->quantity <= setting('site.stock_threshold') && $annonces->quantity > 0) {
$stockLevelStatus = 'Low Stock';
$stockLevelBadge = 'badge-warning';
} else {
$stockLevelStatus = 'Not Avialable';
$stockLevelBadge = 'badge-danger';
}
return view('annonces.details')->with([
'annonces' => $annonces,
'stockLevelStatus' => $stockLevelStatus,
'stockLevelBadge' => $stockLevelBadge,
'mightAlsoLike' => $mightAlsoLike,
]);
}
balde:
<div>
<div class="badge badge-pill {{$stockLevelBadge}}">
{{$stockLevelStatus}}
</div>
</div>
How to display blog post with HTML code snippets in Laravel
There is no straightforward way of doing this by using standard Laravel/Blade output options. However it's possible to accomplish it with a little bit of extra code.
1. Why is this happening
Neither <pre>
or <code>
is stopping the browser to interpret the text inside as html code. They have different purpose: one is to tell the browser that the whitespaces are important and the other to tell that the content is some computer code and needs to be shown with different styling. In both cases if valid HTML code is inside the tags it will be treated as HTML.
By the way it's mentioned in Prism documentation that you need to escape the content:
Note: You have to escape all < and & characters inside < code > elements
(code blocks and inline snippets) with < and & respectively, or
else the browser might interpret them as an HTML tag or entity. If you
have large portions of HTML code, you can use the Unescaped Markup
plugin to work around this.
2. Solutions
There are different ways of solving your issue. You can either modify the input before saving it to the database and then just print the unescaped contents or modify the output and make sure you have escaped only the text in the <code>
tag.
Because we don't know much about the input method you use let's focus on the second option to modify the output.
A. PrismJS
Their documentation points to a solution where you can use the Unescaped markup plugin to solve your issue. I don't have any experience with it, but the slogan says "Write markup without having to escape anything.", so it seems it will do the work.
You only need to include the plugin and then you have two options: to swap <pre><code>
for <script>
or to use HTML-comment to wrap your code (if you don't have other comments in the code
Just look at their examples for detailed information
B. PHP
You can use PHP to parse the text from the database and escape the content of the needed elements. In your case this is the code
element. You will need to write your own implementation or use the one that I wrote for your case.
Then you can just do:
{!! Houdini::escape($content) !!}
Include or autoload the following class:
class Houdini
{
/**
* Escape the html characters inside a given HTML element
*
* @param string $text The text we are trying to clean
* @param string $element The name of the elements to be escaped
* @param bool $fix Should we try to make the text a valid HTML by wrapping it with divs
*
* @return string
*/
public static function escape($text, $element = 'code', $fix = true) {
$dom = new DOMDocument;
$dom->loadXML($fix ? '<div>' . $text . '</div>' : $text);
$nodes = $dom->getElementsByTagName($element);
foreach ($nodes as $node) {
$content = '';
foreach ($node->childNodes as $child) {
$content .= self::escapeRecursively($child);
}
$node->nodeValue = htmlspecialchars($content);
}
return $dom->saveHTML();
}
/**
* Escape node and note contents
*
* @param $node
* @return string
*/
protected static function escapeRecursively($node) {
if ($node instanceof DOMText)
return $node->textContent;
$content = "<$node->nodeName>";
foreach ($node->childNodes as $child) {
$content .= self::escapeRecursively($child);
}
return "$content</$node->nodeName>";
}
}
C. JavaScript
You can include the following javascript code which will loop trough all the <code>
elements and set the innerHtml as the innerText.
document.querySelectorAll("code").forEach(el => el.innerText = el.innerHTML);
Note: If you keep the paragraphs in the database separated only with new lines and not wrapped in <p>
you will have issues using this solution and nl2br()
together.
D. Deprecated <xmp>
<pre><code class="lang-html">
<xmp><div>test</div></xmp>
</code></pre>
There WAS after all an HTML tag specifically to show example HTML code as it is, but it was deprecated in HTML 3.2, BUT it seems the tag is widely supported and wrapping the code contents can be a quick and dirty solution for your case. You can see the support tables here: https://caniuse.com/?search=xmp
Read more here: https://html.com/tags/xmp/#ixzz74T0AJctF
You can accomplish this by adding the tags before saving to the database or when printing the output with JavaScript on the client side or with PHP before passing it to the blade template.
3. Other StackOverflow posts that helped me for this answer
- Escape HTML Chars In the Pre Tag
- How to show <div> tag literally in <code>/<pre> tag?
Unable to display raw html Data in blade file with substr function
this show html characters in your html but you cant substring that before rendering
you can use that code to delete special characters and substring
{{ substr(strip_tags($blog->description),0,200) }}
Related Topics
What Is the Most Accurate Way to Retrieve a User'S Correct Ip Address in PHP
Asynchronous Shell Exec in PHP
Seo Friendly Url Results in CSS Img and Js Not Working
Is "MySQLi_Real_Escape_String" Enough to Avoid SQL Injection or Other SQL Attacks
Apache Is Downloading PHP Files Instead of Displaying Them
Ajax Request Callback Using Jquery
How to Change the Session Timeout in PHP
PHP Method Chaining or Fluent Interface
How to Use Multiple Databases in Laravel
Target Class Controller Does Not Exist - Laravel 8
Convert PHP Array to JavaScript
How to Bind an Array of Strings With MySQLi Prepared Statement
How to Validate an Email Address in PHP
How to Get a File'S Extension in PHP
Allowed Memory Size of 33554432 Bytes Exhausted (Tried to Allocate 43148176 Bytes) in PHP
How to Solve PHP Error 'Notice: Array to String Conversion In...'