61 posts / categories / feed

Laravel Blade Adding Multiple Yields

While working on a project, I was trying to find out the possibility of adding multiple yields to a layout, e.g. if I have a javascript that I would like to run in a page, but not the others, so as to save some resources, this could be easily done with having multiple yields on a blade template layout. Here is how to go about doing it.

For example if I have a view structure like so:


/layouts

 |------> default.blade.php

/includes

 |------> default-js.blade.php

/pages

 |-------> home.blade.php

This is the code for my layout blade template, default.blade.php:


<!DOCTYPE html>
<html>
<head></head>

<body>

<div id="main">

    @yield('content')

</div>

@include('includes.default-js')

@yield('more-js', '')
// this will set the default value as '', useful for those pages 
// that you didn't want to set, or forget to set any values to this section.

</body>

</html>

With that, you can define the two sections within the home.blade.php:


@extends('layouts/default')

@section('content')

    <h1>Hello World</h1>

@stop

@section('more-js')

    <script type="text/javascript">// my first addon javascript</script>

    <script type="text/javascript">// my second addon javascript</script>

@stop