我正在阅读Laravel Blade文档,我不知道如何在模板中分配变量以供以后使用。我不能使用{{$old_section = "whatever"}},因为这将会返回"whatever",而我不想这样做。
我知道我可以做<?PHP $old_section = "whatever";>,但这并不优雅。
在Blade模板中是否有更好、更优雅的方式来做到这一点?
我正在阅读Laravel Blade文档,我不知道如何在模板中分配变量以供以后使用。我不能使用{{$old_section = "whatever"}},因为这将会返回"whatever",而我不想这样做。
我知道我可以做<?PHP $old_section = "whatever";>,但这并不优雅。
在Blade模板中是否有更好、更优雅的方式来做到这一点?
当前回答
适用于所有版本的刀锋。
{{--*/ $optionsArray = ['A', 'B', 'C', 'D','E','F','G','H','J','K'] /*--}}
其他回答
我将扩展@Pim给出的答案。
将此添加到AppServiceProvider的引导方法中
<?php
/*
|--------------------------------------------------------------------------
| Extend blade so we can define a variable
| <code>
| @set(name, value)
| </code>
|--------------------------------------------------------------------------
*/
Blade::directive('set', function($expression) {
list($name, $val) = explode(',', $expression);
return "<?php {$name} = {$val}; ?>";
});
这样就不会暴露编写任何php表达式的能力。
你可以像这样使用这个指令:
@set($var, 10)
@set($var2, 'some string')
在我看来,最好将逻辑保存在控制器中,并将其传递给视图使用。这可以通过使用'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
在laravel4中,您可以使用模板注释语法来定义/设置变量。
注释语法是{{——这里的任何东西都是Comment——}},它被blade引擎渲染为
<?PHP /* anything这里是comment */ ?>
比如,我们可以用它来定义变量
{{-- */$i=0;/* --}}
会被刀片渲染吗 < ?PHP /* */$i=0;/* */ ?>为我们设置变量。 无需更改任何代码行。
从Laravel 5.2.23开始,你有了@php Blade指令,你可以使用内联或作为块语句:
@php($old_section = "whatever")
or
@php
$old_section = "whatever"
@endphp
在Blade模板引擎中可以通过以下方式设置变量: 1. 通用PHP块 设置变量:<?php $hello = " hello World!";? > 输出:{{$你好}} 2. Blade PHP块 设置变量:@php $hello = " hello World!";@endphp 输出:{{$你好}}