Laravel Blade is packed with features that make creating dynamic layouts and reusable components seamless. Among these, @stack, @push, and @endpush stand out as powerful tools for managing dynamic content like CSS or JavaScript on a per-page basis.
What Are @stack, @push, and @endpush?
@stack: Defines a placeholder in the layout where content from the stack will be rendered.
@push and @endpush: Add content to a named stack from child views or components.
Basic Usage Example
Here’s how they work together:
Layout File (Master Template):
blade
<!DOCTYPE html>
<html>
<head>
<title>My App</title>
<link rel="stylesheet" href="/default-styles.css">
@stack('css') <!-- Placeholder for additional CSS -->
</head>
<body>
<div class="content">
@yield('content')
</div>
@stack('scripts') <!-- Placeholder for additional scripts -->
</body>
</html>
Child View:
blade
@extends('layout')
@section('content')
<h1>Welcome to My App</h1>
@endsection
@push('css')
<link rel="stylesheet" href="/custom-styles.css">
@endpush
@push('scripts')
<script src="/custom-script.js"></script>
@endpush
Rendered Output:
html
<!DOCTYPE html>
<html>
<head>
<title>My App</title>
<link rel="stylesheet" href="/default-styles.css">
<link rel="stylesheet" href="/custom-styles.css">
</head>
<body>
<div class="content">
<h1>Welcome to My App</h1>
</div>
<script src="/custom-script.js"></script>
</body>
</html>
Why Use Them?
Cleaner Code: Keep your layout template minimal and dynamic.
Page-Specific Assets: Add CSS or JS only when needed for a specific page.
Reusable Components: Push required styles/scripts dynamically based on the components used.
Tips for Developers
Meaningful Names: Use stack names like css, scripts, or meta for clarity.
Order Matters: Content is rendered in the order it’s pushed, so plan dependencies carefully.
Perfect for Modular Design: Works great with reusable components or widgets.
Advanced Example: Multiple Stacks
Layout File:
blade
<head>
<title>@yield('title', 'Default Title')</title>
@stack('meta') <!-- Metadata Stack -->
@stack('css') <!-- CSS Stack -->
</head>
<body>
@yield('content')
@stack('scripts') <!-- Scripts Stack -->
</body>
@push('meta')
<meta name="description" content="Custom page description">
@endpush
@push('css')
<link rel="stylesheet" href="/page-specific-styles.css">
@endpush
@push('scripts')
<script src="/page-specific-scripts.js"></script>
@endpush
Conclusion
With @stack, @push, and @endpush, you can dynamically manage assets in Laravel Blade templates. These directives are perfect for building modular and scalable applications.
Start using them today to make your Laravel projects cleaner and more efficient!
Top comments (0)