Laravel Blade @yield and escaping
Asked Answered
S

3

6

In Laravel 5 I have a master template containing:

<title>@yield('title') | Site Name</title>

And in my view I have:

@extends('master')

@section('title', $client->name)

...

The problem is, the @yield does not escape the data passed to it. So far, the only solution I've found is to manually escape the data like so:

@section('title', e($client->name))

Is this the best method? It means I have to manually escape data on every view that I use a variable. I don't see a way to escape the @yield directive from the master template - using {{ }} or e() around the @yield doesn't work.

Semiyearly answered 24/11, 2015 at 18:6 Comment(1)
I didn’t realise @​yield-ed values weren’t escaped. Thanks for pointing that out!Polad
P
13

Why not do the following:

@section('title') {{$client->name}} @endsection

This is at least then consistent with escaping data in the rest of your views. The way you have it, you may be very likely to miss an e(). With the above, you will be able to see immediately when you render the view if you have not escaped.

UPDATE

What about using the raw PHP:

<title> <?php echo e($__env->yieldContent('title')); ?> | Site Name</title>

This is what the blade template engine replaces the @yield with, but I've add the escape helper.

This should mean you don't need to escape @section. I think this will work, haven't tried it.

Plagioclase answered 24/11, 2015 at 18:36 Comment(1)
This would get my vote. Does @Semiyearly have a reason for not doing it this way?Hypoderma
T
2

In my case the problem was is that it's actually escaped the string I passed, like this:

@section('title', 'String with \' string')

In result in actual HTML you'll see &#039; instead of actual '.

Workaround for this is to write section like this:

@section('title'){!! "String with ' string" !!}@endsection
Themselves answered 26/11, 2021 at 9:59 Comment(0)
T
0

Do

@section('title')
 {{ $client->name }}
@stop
Taboret answered 24/11, 2015 at 18:35 Comment(2)
Is @stop still supported in Laravel 5? I was under the impression they removed it.Semiyearly
I think \@endsection is technically the right way to do this, but I haven't had any trouble with \@stop in my L5 apps.Hypoderma

© 2022 - 2024 — McMap. All rights reserved.