Laravel Blade adding double quotes around HTML attributes
I'm writing a custom Laravel Helper that generates the img HTML tag dynamically (I use this to generate the img srcset and size attributes, because I use a CDN). But when returning the generated string, double quotes are added around the attributes. Spaces in attribute values are also broken into smaller attributes.
<img src=""https://ik.imagekit.io/sdqrv2ex9bq/Rosa_de_Saron/cremacao_slide.jpg?ik-sdk-version=php-2.0.0"srcset="https://ik.imagekit.io/sdqrv2ex9bq/Rosa_de_Saron/tr:w-768:/cremacao_slide.jpg?ik-sdk-version=php-2.0.0" 768\w,https:="" ik.imagekit.io="" sdqrv2ex9bq="" rosa_de_saron="" tr:w-1366:="" cremacao_slide.jpg?ik-sdk-version="php-2.0.0" 1366\w"="" alt="Pessoa com urna funerária" width="1366" height="768">
This is my Helper:
function image_cdn($path, $sizes=[], $transform=[]){
//CRIA OBJETO DO SDK
$image = new ImageKit(
env('IMAGEKIT_PUB_KEY'),
env('IMAGEKIT_PRIV_KEY'),
env('IMAGEKIT_ENDPOINT')
);
//ADICIONA URL DEFAULT
$tagImg = ' src="'.$image->url([
'path'=>$path,
'transformation'=>$transform
]).'"';
//ORDENA OS INTENS DO ARRAY
$sizes = Arr::sort($sizes);
//LOOP PARA GERAR CADA SIZE ENVIADO (SE HOUVER)
foreach($sizes as $size){
//GERA URL DA IMAGEM COM A TRANSFORMAÇÃO DO WIDTH
$imageSet[] = $image->url([
'path'=>$path,
'transformation'=>[
['width'=>$size],
$transform
]
])." $size\w";
//GERA O ATRIBUTO SIZES
$imageSize[] = "(max-width: $size\px) $size\px";
}
//SE FORAM SIZES PARA A IMAGEM ADICIONA ELES NA TAG GERADA
$tagImg .= isset($imageSet) ? 'srcset="'.implode(',',$imageSet).'"' : '';
//RETORNO
return $tagImg;
}
The Helper call:
<img {{ image_cdn('cremacao_slide.jpg',[768,1366]) }} alt="Pessoa com urna funerária" width="1366" height="768">
The other option, if you want to keep using the {{ }}
escaped echo syntax, is to put your string into an HtmlString
object. The e
helper method, which escapes the strings for the echos, checks if what is being passed is Htmlable
and will directly return the call to toHtml
on it instead of escaping the content:
function returningSomeHtml(...)
{
return new Illuminate\Support\HtmlString(...the HTML Content...);
}
{{ returningSomeHtml(...) }}
Your function is returning a fully built attribute that you want to display as-is. The {{ }}
blade syntax, however, will escape your special characters.
You need to use the {!! !!}
syntax to print your value without blade escaping it.
<img {!! image_cdn('cremacao_slide.jpg',[768,1366]) !!} alt="Pessoa com urna funerária" width="1366" height="768">
On a complete side note, I see your function is using the env()
function directly. The env()
function should only be used inside the config files, and the config values should be accessed inside your function. As it is written right now, this code will break if you ever cache your config (ex: in production).