Laravel Blade:@stack

Laravel Blade 模板中的 @stack 标签对于指定子视图可能需要的 JavaScript 或 CSS 文件等特别有用。

stack 顾名思义是堆栈的意思,这里的操作则是入栈。

基本使用

1
2
3
4
5
// In your layout
<head>
<!--comment0-->
@stack('scripts')
</head>
1
2
3
4
// In a child view
@push('scripts')
<script src="/example.js"></script>
@endpush

进阶使用

@prepend

加入到堆栈的开始

1
2
3
@prepend('scripts')
<script src="/first-to-load.js"></script>
@endprepend

@pushIf

根据条件入栈

1
2
3
@pushIf($shouldPushScript, 'scripts')
<script src="/conditional-script.js"></script>
@endPushIf

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// resources/views/layouts/app.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>@yield('title', 'My App')</title>
<link rel="stylesheet" href="/app.css">
@stack('styles')
</head>
<body>
<nav>
<!--comment1-->
</nav>

<main>
@yield('content')
</main>

<footer>
<!--comment2-->
</footer>

<script src="/app.js"></script>
@stack('scripts')
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// resources/views/posts/show.blade.php
@extends('layouts.app')

@section('title', 'View Post')

@section('content')
<h1>{{ $post->title }}</h1>
<p>{{ $post->content }}</p>
@endsection

@push('styles')
<link rel="stylesheet" href="/posts.css">
@endpush

@push('scripts')
<script src="/posts.js"></script>
@endpush
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// resources/views/posts/create.blade.php
@extends('layouts.app')

@section('title', 'Create Post')

@section('content')
<h1>Create a New Post</h1>
<!--comment3-->
@endsection

@push('styles')
<link rel="stylesheet" href="/markdown-editor.css">
@endpush

@push('scripts')
<script src="/markdown-editor.js"></script>
<script>
initializeMarkdownEditor();
</script>
@endpush

参考:

https://www.harrisrafto.eu/mastering-blade-stacks-organizing-your-laravel-views-with-precision