我正在阅读Laravel Blade文档,我不知道如何在模板中分配变量以供以后使用。我不能使用{{$old_section = "whatever"}},因为这将会返回"whatever",而我不想这样做。

我知道我可以做<?PHP $old_section = "whatever";>,但这并不优雅。

在Blade模板中是否有更好、更优雅的方式来做到这一点?


当前回答

Laravel 5你可以很容易做到这一点。见下文

{{--*/ @$variable_name = 'value'  /*--}}

其他回答

如果你有PHP 7.0:

最简单有效的方法是在括号内赋值。

规则很简单:使用变量是否超过一次?然后在括号内声明它第一次使用,保持冷静,继续下去。

@if(($users = User::all())->count())
  @foreach($users as $user)
    {{ $user->name }}
  @endforeach
@else
  There are no users.
@endif

是的,我知道@forelse,这只是一个演示。

由于变量现在被声明为和当它们被使用时,不需要任何刀片工作区。

Laravel 5你可以很容易做到这一点。见下文

{{--*/ @$variable_name = 'value'  /*--}}

在我看来,最好将逻辑保存在控制器中,并将其传递给视图使用。这可以通过使用'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

在刀片文件中,可以使用这种格式

@php
  $i++
@endphp

拉拉维尔 7 :

{{ $solution = "Laravel 7 is awesome and easy to use !!" }}