我正在阅读Laravel Blade文档,我不知道如何在模板中分配变量以供以后使用。我不能使用{{$old_section = "whatever"}},因为这将会返回"whatever",而我不想这样做。
我知道我可以做<?PHP $old_section = "whatever";>,但这并不优雅。
在Blade模板中是否有更好、更优雅的方式来做到这一点?
我正在阅读Laravel Blade文档,我不知道如何在模板中分配变量以供以后使用。我不能使用{{$old_section = "whatever"}},因为这将会返回"whatever",而我不想这样做。
我知道我可以做<?PHP $old_section = "whatever";>,但这并不优雅。
在Blade模板中是否有更好、更优雅的方式来做到这一点?
当前回答
你可以使用我发布的软件包:https://github.com/sineld/bladeset
然后你可以轻松地设置你的变量:
@set('myVariable', $existing_variable)
// or
@set("myVariable", "Hello, World!")
其他回答
在我看来,最好将逻辑保存在控制器中,并将其传递给视图使用。这可以通过使用'View::make'方法来实现。我目前正在使用Laravel 3,但我非常确定它在Laravel 4中是相同的方式。
public function action_hello($userName)
{
return View::make('hello')->with('name', $userName);
}
or
public function action_hello($first, $last)
{
$data = array(
'forename' => $first,
'surname' => $last
);
return View::make('hello', $data);
}
'with'方法是可链的。然后你可以像这样使用上面的语句:
<p>Hello {{$name}}</p>
更多信息请点击这里:
http://three.laravel.com/docs/views
http://codehappy.daylerees.com/using-controllers
你可以使用我发布的软件包:https://github.com/sineld/bladeset
然后你可以轻松地设置你的变量:
@set('myVariable', $existing_variable)
// or
@set("myVariable", "Hello, World!")
在刀片文件中,可以使用这种格式
@php
$i++
@endphp
laravel文档https://laravel.com/docs/5.8/blade#php 你可以这样做:
@php
$my_variable = 123;
@endphp
在laravel4中,您可以使用模板注释语法来定义/设置变量。
注释语法是{{——这里的任何东西都是Comment——}},它被blade引擎渲染为
<?PHP /* anything这里是comment */ ?>
比如,我们可以用它来定义变量
{{-- */$i=0;/* --}}
会被刀片渲染吗 < ?PHP /* */$i=0;/* */ ?>为我们设置变量。 无需更改任何代码行。