I have a string returned to one of my views, like this:
$text = '<p><strong>Lorem</strong> ipsum dolor <img src="images/test.jpg"></p>'
I'm trying to display it with Blade:
{{$text}}
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.
You need to use
{!! $text !!}
The string will auto escape when using {{ $text }}.
For laravel 5
{!!html_entity_decode($text)!!}
Figured out through this link, see RachidLaasri answer
You can try this:
{!! $text !!}
You should have a look at: http://laravel.com/docs/5.0/upgrade#upgrade-5.0
Please use
{!! $test !!}
Only in case of HTML while if you want to render data, sting etc. use
{{ $test }}
This is because when your blade file is compiled
{{ $test }} is converted to <?php echo e($test) ?>
while
{!! $test !!} is converted to <?php echo $test ?>
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: {{ $someObject }} (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 {{ $product->getProductDescription() }}.
Of course be responsible when directly rendering raw html on page.
When your data contains HTML tags then use
{!! $text !!}
When your data doesn't contain HTML tags then use
{{ $text }}
Try this. It worked for me.
{{ html_entity_decode($text) }}
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
{!! $text !!}
The is Second way
<td class="nowrap">
#if( $order->status == '0' )
<button class="btn btn-danger">Inactive</button>
#else
<button class="btn btn-success">Active</button>
#endif
</td>
The third and proper way for use ternary operator on blade
<td class="nowrap">
{!! $order->status=='0' ?
'<button class="btn btn-danger">Inactive</button> :
'<button class="btn btn-success">Active</button> !!}
</td>
I hope the third way is perfect for used ternary operator on blade.
you can do with many ways in laravel 5..
{!! $text !!}
{!! html_entity_decode($text) !!}
Use {!! $text !!}to display data without escaping it. Just be sure that you don’t do this with data that came from the user and has not been cleaned.
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:
|---------------------|------------------|
| Character | Entity |
|---------------------|------------------|
| & | & |
|---------------------|------------------|
| < | < |
|---------------------|------------------|
| > | > |
|---------------------|------------------|
| " | " |
|---------------------|------------------|
For example, assume we have the following php statement:
$hello = "<b>Hello</b>";
Passed into blade as {{ $hello }} would yield the literal string you passed:
<b>Hello</b>
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:
{!! $hello !!}
Note that we only use one curly brace.
The output of the above would yield:
Hello
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:
$hello = "<b> Hello <b>";
We could now add this function to our escaped blade statement:
{!! html_entity_decode($hello) !!}
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 >
which would yield
Hello
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.
This works fine for Laravel 5.6
<?php echo "$text"; ?>
In a different way
{!! $text !!}
It will not render HTML code and print as a string.
For more details open link:- Display HTML with Blade
By default, Blade {{ }} statements are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax:
According to the doc, you must do the following to render your html in your Blade files:
{!! $text !!}
Be very careful when echoing content that is supplied by users of your application. You should typically use the escaped, double curly brace syntax to prevent XSS attacks when displaying user supplied data.
If you want to escape the data use
{{ $html }}
If don't want to escape the data use
{!! $html !!}
But till Laravel-4 you can use
{{ HTML::link('/auth/logout', 'Sign Out', array('class' => 'btn btn-default btn-flat')) }}
When comes to Laravel-5
{!! HTML::link('/auth/logout', 'Sign Out', array('class' => 'btn btn-default btn-flat')) !!}
You can also do this with the PHP function
{{ html_entity_decode($data) }}
go through the PHP document for the parameters of this function
html_entity_decode - php.net
Try this, It's worked:
#php
echo $text;
#endphp
For who using tinymce and markup within textarea:
{{ htmlspecialchars($text) }}
On controller.
$your_variable = '';
$your_variable .= '<p>Hello world</p>';
return view('viewname')->with('your_variable', $your_variable)
If you do not want your data to be escaped, you may use the following syntax:
{!! $your_variable !!}
Output
Hello world
{!! !!} is not safe.
Read here: https://laravel.com/docs/5.6/blade#displaying-data
You can try:
#php
echo $variable;
#endphp
If you use the Bootstrap Collapse class sometimes {!! $text !!}
is not worked for me but {{ html_entity_decode($text) }} is worked for me.
I have been there and it was my fault. And very stupid one.
if you forget .blade extension in the file name, that file doesn't understand blade but runs php code. You should use
/resources/views/filename.blade.php
instead of
/resources/views/filename.php
hope this helps some one
Related
I have HTML code with variable in database I want to display the code with html design and variable data in blade
Database Code
<ul class="dropdown-menu dropdown-menu-right">
<li>
#foreach ($block->options as $option)
<a>{{$option->name}}</a>
#endforeach
</li>
</ul>
Blade View
#foreach ($blocks as $block)
{!! $block !!}
#endforeach
I have already display the html code but the variable still as strings
enter image description here
Before saving your data in database, use the php built-in function htmlentities() on the html code string like this:
$html_code = '<p class="any-class">Lorem Ipsum / Random Text</p>';
$encode = htmlentities($html_code);
/* Insert the $encode in the database cell where you want to store html */
And then when displaying the cell data with html tags using blade, you do this {{!! html_entity_decode($block) !!}}
This will work fine!!! Cheers!!
I am using twig to render a view and I am using the striptags filter to remove html tags.
However, html special chars are now rendered as text as the whole element is surrounded by "".
How can I either strip special chars or render them, while still using the striptags function ?
Example :
{{ organization.content|striptags(" >")|truncate(200, '...') }}
or
{{ organization.content|striptags|truncate(200, '...') }}
Output:
"QUI SOMMES NOUS ? > NOS LOCAUXNOS LOCAUXDepuis 1995, Ce lieu chargé d’histoire et de tradition s’inscrit dans les valeurs"
If it could help someone else, here is my solution
{{ organization.content|striptags|convert_encoding('UTF-8', 'HTML-ENTITIES') }}
You can also add a trim filter to remove spaces before and after.
And then, you truncate or slice your organization.content
EDIT November 2017
If you want to keep the "\n" break lines combined with a truncate, you can do
{{ organization.content|striptags|truncate(140, true, '...')|raw|nl2br }}
I had a similar issue, this worked for me:
{{ variable |convert_encoding('UTF-8', 'HTML-ENTITIES') | raw }}
I was trying some of, among others, these answers:
{{ organization.content|striptags|truncate(200, true) }}
{{ organization.content|raw|striptags|truncate(200, true) }}
{{ organization.content|striptags|raw|truncate(200, true) }}
etc.
And still got strange characters in the final form. What helped me, is putting the raw filter on the end of all operations, i.e:
{{ organization.content|striptags|truncate(200, '...')|raw }}
Arf, I finally found it :
I am using a custom twig filter that just applies a php function:
<span>{{ organization.shortDescription ?: php('html_entity_decode',organization.content|striptags|truncate(200, '...')) }}</span>
Now it renders correctly
My php extension:
<?php
namespace AppBundle\Extension;
class phpExtension extends \Twig_Extension
{
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('php', array($this, 'getPhp')),
);
}
public function getPhp($function, $variable)
{
return $function($variable);
}
public function getName()
{
return 'php_extension';
}
}
2022 update | tested with Drupal 8.6.16
I tried the top voted recommendation. It worked ok with some symbols but not with others.
raw filter seems to be working ok with all special characters.
like so
{{ organization.content|striptags|raw }}
The best way to do this is :
{{ organization.content|striptags|truncate(200, '...')|raw }}
With |raw always at the end.
Don't use convert_encoding('UTF-8', 'HTML-ENTITIES'), you will encounter iconv issues.
When I thought none of the above answers were working for me (convert_encoding running into iconv() issues in Drupal 9, and I thought raw, but because applying it on the argument side of an {% embed %} — as opposed to in the embedded template itself — didn't seem to help), another approach that seemed to work for me was:
{% autoescape false %}
{{ organization.content|striptags|truncate(200, '...') }}
{% endautoescape %}
with that false part being key.
I had the same problem, I resolved it byt this function below, using strip_tags.
<?php
namespace AppBundle\Extension;
class filterHtmlExtension extends \Twig_Extension
{
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('stripHtmlTags', array($this, 'stripHtmlTags')),
);
}
public function stripHtmlTags($value)
{
$value_displayed = strip_tags($value);
return $value_displayed ;
}
public function getName()
{
return 'filter_html_extension';
}
}
I would like to combine the Laravel model binding properties with the easy jQuery Validation plugin, if that is possible.
I can't figure out how to add the 'required' attribute to the blade syntax.
Here is normal form syntax with the "required" attribute:
<input type="text" name="title" required>
Laravel Blade syntax
{{ Form:: text('title', null, array('class' => 'form-control')) }}
Any help would be appreciated.
required is a normal HTML input attribute. The only difference is that it doesn't have different values -- it's either present or it's not, which makes it the so-called boolean attribute.
Anyway, this should do the trick:
{{ Form:: text('title', null, array('class' => 'form-control', 'required' => '')) }}
See more here.
Can someone help to rewrite this, from HTML to Laravel4?
</i></span> Home
The route name for that page is just '/'.
I know how to write simple link in Laravel:
{{ HTML::link('/','Home) }}
But how can I add the span class with the font-awesome icon?
I'd just put the link in the href.
<span><i class="icon-home"></i></span> Home
No need to generate all the rest through Laravel.
What #Dries suggests is simple and very straightforward, but you really want to have it done entirely via Laravel, I would suggest writing a HTML macro, especially if you want more complex html structures to be involved. For example, here is a macro for <a><img /></a> structure:
HTML::macro('image_link', function($url = '', $img='img/', $alt='', $param = false, $active=true, $ssl=false)
{
$url = $ssl==true ? URL::to_secure($url) : URL::to($url);
$img = HTML::image($img,$alt);
$link = $active==true ? HTML::link($url, '#', $param) : $img;
$link = str_replace('#',$img,$link);
return $link;
});
You could read more about it here: http://forums.laravel.io/viewtopic.php?pid=10467
{!! HTML::decode(link_to(URL::previous(),
'<i class="fa fa-chevron-left" aria-hidden="true"></i> Back',
['class' => 'btn btn-primary'])) !!}
I'm trying to have CakePHP output a link that looks like this:
<a href="/foo/bar" class="some other classes">
<span class="icon new"></span>FooBar</a>
So I use the following code in my view
<?php
echo $this->Html->link(
$this->Html->tag('span', null, array('class' => 'icon new')) . "FooBar",
array('controller' => 'foo', 'action' => 'bar'),
array('class' => 'some other classes', 'escape' => false)
);
?>
However CakePHP outputs the following:
<a href="/foo/bar" class="some other classes">
<span class="icon new">FooBar</span></a>
Which breaks my design. How can I get CakePHP to append "FooBar" after the <span> tags?
EDIT: Its also worth mentioning that I know a <span> tags shouldn't be within an anchor tag usually, but in the case its a must.
You need to use an empty string in stead of null as the text for the span, then your code will work as expected.
Looking at the source code of the HtmlHelper, null is treated as a 'special' value, causing only the opening tag of the span to be created. You can see this in this line:
https://github.com/cakephp/cakephp/blob/2.3.2/lib/Cake/View/Helper/HtmlHelper.php#L906
Change your code to this and it should work;
echo $this->Html->link(
$this->Html->tag('span', '', array('class' => 'icon new')) . "FooBar",
array('controller' => 'foo', 'action' => 'bar'),
array('class' => 'some other classes', 'escape' => false)
);
Additional explanation of the closing </span>
A bit of explanation, for those who wonder:
The closing </span> in your example is actually not present in the output generated by CakePHP, but automatically 'added' by your browser. If you view the source of the HTML in your browser, you'll see that this is what is actually in your HTML:
<a href="/foo/bar" class="some other classes">
<span class="icon new">FooBar</a>
As you can see, no closing 'span'
Because the <span> is not closed, the browser will try to correct this error and automatically assumes that you 'forgot' to close it. Therefor it will add a closing </span> before the next tag it finds (in this case the closing </a>).
The 'inspector' in your browser will always show the HTML that the browser uses to render the output. This includes automatic corrections made by the browser and dynamically generated elements (e.g. Elements added via JavaScript).
To check the output of your PHP scripts, always view the source, not the inspector
In this situation, I've avoided the CakePHP helpers entirely because the markup becomes really messy and cannot take advantage of autocomplete or validation within your IDE.
I usually do something like this:
<span class="icon-new"></span>Foobar
This looks a little overkill for me. Just do this:
echo $this->Html->link(
"<span class="icon new"></span> FooBar",
array('controller' => 'foo', 'action' => 'bar'),
array('class' => 'some other classes', 'escape' => false)
);
I've been using CakePHP for 4 years and I don't see the benefit of using tag in this instance.
Would you be able to use regular PHP in this case?
I am thinking you could do it like this:
<?PHP
echo('<span class="' . 'icon new' . '"></span>' . 'FooBar' . '')
?>