Reputation: 457
I have master layout of laravel blade template main.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>@yield('title','My Site')</title>
</head>
<body>
@yield('container','Content area')
{{ HTML::script('assets/js/jquery-1.9.0.js') }}
</body>
</html>
I extended it for another view index.blade.php
@extend('main')
I want to add javascript links to master layout(main.blade.php
) if exists in child layout(index.blade.php
)
added code in index.blade.php
$extraJs = array('plugins1.js','plugins2.js');
@section('extraJs')
{{ $extraJs }}
@stop
So, How can I add javascript to master layout if exists in child blade?
In php:
<?php
if(isset($extraJs)):
foreach($extraJs as $js):
?>
<script src="assets/js/<?php echo $js ?>" type="text/javascript" />
<?php endforeach; endif; ?>
Upvotes: 2
Views: 1425
Reputation: 152880
I wouldn't really encourage this method but since you asked. It is definitely possible to pass something "up" in the view tree. You can just define a PHP variable in your view and it will be available anywhere in the layout.
<?php $extraJs = array('plugins1.js','plugins2.js'); ?>
@if(isset($extraJs))
@foreach($extraJs as $js)
<script src="{{ asset('assets/js/'.$js) }}" type="text/javascript" />
@endforeach
@endif
As you can see I also converted your code in the layout to blade and made use of the asset()
function to generate absolute URLs
Note Instead of doing it this way there are other methods. For example View composers or defining the plugins in the controller.
Upvotes: 1
Reputation: 25384
You can just add a yield in your main.blade.php
, like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>@yield('title','My Site')</title>
</head>
<body>
@yield('container','Content area')
{{ HTML::script('assets/js/jquery-1.9.0.js') }}
@yield('javascripts')
</body>
</html>
Then, in your child layout, you add a section for it, like you did. For example:
@section('javascripts')
@foreach($scripts as $script)
{{ HTML::script('ets/js/' . $script) }}
@endforeach
@stop
If you add another child view which doesn't need to use extra javascripts, Laravel won't complain because the section is optional.
Upvotes: 1