简体   繁体   English

Laravel 4 Blade @include变量

[英]Laravel 4 Blade @include variable

I was trying to do include with Laravel blade, but the problem is it can't pass the variable. 我试图做include与Laravel刀片,但问题是它不能传递变量。 Here's my example code: 这是我的示例代码:

file_include.blade.php file_include.blade.php

<?php
  $myvar = "some text";

main.blade.php main.blade.php

@include('file_include')
{{$myvar}}

When I run the file, it return the error "Undefined variable: myvar". 当我运行该文件时,它返回错误“Undefined variable:myvar”。 So, how can I pass the variable from the include file to the main file? 那么,我如何将包含文件中的变量传递给主文件?

Thank you. 谢谢。

Why would you pass it from the include to the calling template? 为什么要将它从包含传递给调用模板? If you need it in the calling template, create it there, then pass it into the included template like this: 如果你在调用模板中需要它,在那里创建它,然后将它传递到包含的模板,如下所示:

@include('view.name', array('some'=>'data'))

Above code snippet from http://laravel.com/docs/templates 以上代码片段来自http://laravel.com/docs/templates

Unfortunately Laravel Blade engine doesn't support what you expected!.But a little traditional way you can achieve this! 不幸的是,Laravel Blade引擎不支持您的预期!但是有点传统的方式可以实现这一点!

SOLUTION 1 - without Laravel Blade Engine 解决方案1 - 没有Laravel Blade Engine

Step a: 第一步:

from

file_include.blade.php

to

file_include.php

Step b: 步骤b:

main.blade.php main.blade.php

<?php 
     include('app/views/file_include.php')
?>
{{$myvar}}

SOLUTION 2 with Laravel Blade Engine 使用Laravel Blade Engine 解决方案2

routes.php

$data = array(
'data1'         => "one",
'data2'         => "two",
);

View::share('data', $data); 

Access $data array from Any View like this Any View访问$ data数组

{{ $data['data1'] }}

Output 产量

one

Blade is a Template Engine for Laravel. Blade是Laravel的模板引擎。 So try passing the value from the controller or you may define it in the routes.php for testing purposes. 因此,尝试从控制器传递值,或者您可以在routes.php中定义它以进行测试。

@include is used to include sub-views. @include用于包含子视图。

I think you must understand the variable scope in Laravel Blade template. 我认为您必须了解Laravel Blade模板中的变量范围。 Including a template using @include will inherit all variables from its parent view(the view where it was defined). 使用@include包含模板将从其父视图(定义它的视图)继承所有变量。 But I guess you can't use your defined variables in your child view at the parent scope. 但我想你不能在父范围的子视图中使用你定义的变量。 If you want your variable be available to the parent try use View::share($variableName, $variableValue) it will be available to all views as expected. 如果您希望您的变量可供父级使用,请尝试使用View::share($variableName, $variableValue) ,它将按预期方式用于所有视图。

In this scenarion $myvar would be available only on the local scope of the include call. 在这种情况下, $myvar只能在include调用的本地范围内使用。

Why don't you send the variable directly from the controller? 为什么不直接从控制器发送变量?

我建议你做一个经典的PHP需要,如果你真的想要改变你的变量(那么它是通过引用自动的)

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

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