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

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

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


当前回答

laravel文档https://laravel.com/docs/5.8/blade#php 你可以这样做:

@php
     $my_variable = 123;
@endphp

其他回答

在拉威尔4区

如果你想让变量在你的所有视图中都可以访问,而不仅仅是你的模板,View::share是一个很好的方法(更多信息在这个博客上)。

只需在app/controllers/BaseController.php中添加以下内容

class BaseController extends Controller
{
  public function __construct()
  {                   
    // Share a var with all views
    View::share('myvar', 'some value');
  }
}

现在$myvar将对您的所有视图可用——包括您的模板。

我用它来为我的图像设置特定于环境的资产url。

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

@php
  $i++
@endphp

如果你有PHP 7.0:

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

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

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

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

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

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

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

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