Is there a way to load js into the <head>
section of the page whena subview is loaded. I would like to only load specific JS files based on the view that is being called. I am using the blade template engine.
There is a much easier way to do this using sections and template inheritance.
@extends('layouts.frontend.master')
@section('scripts')
Your Scripts
@stop
@section('content')
Your content
@stop
It's that simple. This is very powerful stuff, as it gives you the ability to set a default but also override it if necessary, keeping your views very clean and minimal.
A better way to do this though would be to do:
@extends('layouts.frontend.master')
@section('head')
@parent
Your Scripts
@stop
@section('content')
Your content
@stop
Then you can remove the @section('scripts') declaration from your master layout. Using the @parent helper will allow you to append content to a section, thus keeping it's default while adding the extra content you have specified in your view.
You can also provide default content for @yield declarations, like so @yield('content', 'Default content').
Check out http://codebright.daylerees.com/blade
First make a common header layout.
app/views/layouts/header.blade.php - header layout
<!DOCTYPE html>
<html>
<head>
<title>{{ $page->title }}</title> {{-- Getting title from $page object, which is passed from route --}}
{{ HTML::style('css/common.css') }}
{{ HTML::script('js/jquery.js') }}
{{ HTML::script('js/common.js') }}
Then page specific script layout.
app/views/layouts/script-about.blade.php - about-page script layout
{{ HTML::script('js/about.js') }}
Then view for specific page.
app/views/about.blade.php - about page
@extends('layouts.master')
@section('content')
<p>About-Us page content goes here</p>
@stop
Then common footer.
app/views/layouts/footer.blade.php - footer layout
</body>
</html>
Then the main layout to render.
app/views/layouts/master.blade.php - main layout
@include('layouts.header')
@include('layouts.script-'.$page->slug) {{-- Getting page name from $page object --}}
</head>
<body>
@yield('content')
@include('layouts.footer')
And from the route, you can pass the $page
variable. You may like this route,
Route::get('{slug}', function($slug) {
$page = Page::where('slug', '=', $slug)->first();
// getting the datas from Page model with pages table where slug = last uri in your address-bar
if ( is_null($page) ) { // if no page in db, call 404
App::abort(404);
}
// render the view with page details
return View::make($page->slug)->with(array('page' => $page));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With