简体   繁体   English

将数组从视图(Blade)传递到laravel中的另一个视图(Blade)

[英]Passing array from view(Blade) to another view(Blade) in laravel

I have master layout of laravel blade template main.blade.php 我有laravel刀片模板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 我将其扩展为另一个视图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 ) 我想将javascript链接添加到主布局( main.blade.php )(如果子布局( index.blade.php )中存在)

added code in index.blade.php 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? 那么,如果子刀片中存在JavaScript,如何将javascript添加到主布局?

In php: 在php中:

<?php 
if(isset($extraJs)): 
foreach($extraJs as $js):
?>
<script src="assets/js/<?php echo $js ?>" type="text/javascript" />
<?php endforeach; endif; ?>

You can just add a yield in your main.blade.php , like this: 您可以在main.blade.php添加一个yield,如下所示:

<!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. 如果您添加了另一个不需要使用额外的JavaScript的子视图,Laravel不会抱怨,因为该部分是可选的。

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变量,它就可以在布局中的任何位置使用。

index.blade.php index.blade.php

<?php $extraJs = array('plugins1.js','plugins2.js'); ?>

main.blade.php main.blade.php

@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 如您所见,我还将布局中的代码转换为Blade并利用asset()函数生成绝对URL

Note Instead of doing it this way there are other methods. 注意除了以这种方式进行操作外,还有其他方法。 For example View composers or defining the plugins in the controller. 例如, 查看作曲家或在控制器中定义插件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM