Laravel 5 中使用 JavaScript 的部分视图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30271376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Partial views with JavaScript in Laravel 5
提问by whoacowboy
I have multiple partial blade files that all require just a little bit of JavaScript. Ideally I'd like the partial to load the JS it needs and the normal JS wouldn't include it. I know you can load it all into one big JS file, but I am wondering if there is a way to have a more elegant solution.
我有多个部分刀片文件,它们都只需要一点点 JavaScript。理想情况下,我希望部分加载它需要的 JS,而普通的 JS 不会包含它。我知道你可以将它全部加载到一个大的 JS 文件中,但我想知道是否有一种更优雅的解决方案。
I'd like the solution below to work for multiple files (it works for one, but not n. The first partial blade encounters is used due to blade's rendering engine).
我希望下面的解决方案适用于多个文件(它适用于一个,但不适用于 n。由于 Blade 的渲染引擎,使用了第一次部分 Blade 遭遇)。
test.page.blade.php
test.page.blade.php
@extends('layouts.default')
@section('title', 'Poses')
@section('content')
<div class="container">
<div class="row">
@include('test.partial.one')
@include('test.partial.two')
</div>
</div>
@stop
@section('javascript')
@include('test.partial.one')
@include('test.partial.two')
@stop
partial test.partial.one.blade.php
部分 test.partial.one.blade.php
@section('content')
<h1>One</h1>
@stop
@section('javascript')
<script>Scripts from one</script>
@stop
partial test.partial.two.blade.php
部分 test.partial.two.blade.php
@section('content')
<h1>Two</h1>
@stop
@section('javascript')
<script>Scripts from two</script>
@stop
回答by peaceman
The solution to your problem is the @parent
directive, which you have to use in your javascript
sections.
您的问题的解决方案是@parent
指令,您必须在您的javascript
部分中使用该指令。
test.page.blade.php
test.page.blade.php
@extends('layouts.default')
@section('title', 'Poses')
@section('content')
<div class="container">
<div class="row">
@include('test.partial.one')
@include('test.partial.two')
</div>
</div>
@stop
@yield('javascript')
test.partial.one.blade.php
test.partial.one.blade.php
@section('content')
<h1>One</h1>
@stop
@section('javascript')
<script>Scripts from one</script>
@parent
@stop
test.partial.two.blade.php
test.partial.two.blade.php
@section('content')
<h1>Two</h1>
@stop
@section('javascript')
<script>Scripts from two</script>
@parent
@stop
For further reference: http://laravel.com/docs/5.0/templates