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

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

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


当前回答

如果你有PHP 7.0:

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

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

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

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

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

其他回答

不建议在视图中这样做,因为没有刀片标签。 如果您确实希望在blade视图中执行此操作,您可以在编写时打开一个php标记,或者注册一个新的blade标记。举个例子:

<?php
/**
 * <code>
 * {? $old_section = "whatever" ?}
 * </code>
 */
Blade::extend(function($value) {
    return preg_replace('/\{\?(.+)\?\}/', '<?php ${1} ?>', $value);
});

你可以在视图文件中设置一个变量,但是它会在你设置的时候被打印出来。不管怎样,有一个变通办法。您可以在未使用的部分中设置该变量。例子:

@section('someSection')
  {{ $yourVar = 'Your value' }}
@endsection

然后{{$yourVar}}将打印你的值到任何你想要它的地方,但当你保存变量时,你不会得到输出。

EDIT:需要命名部分,否则将引发异常。

在我看来,最好将逻辑保存在控制器中,并将其传递给视图使用。这可以通过使用'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.2.23开始,你有了@php Blade指令,你可以使用内联或作为块语句:

@php($old_section = "whatever")

or

@php
    $old_section = "whatever"
@endphp

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

@php
     $my_variable = 123;
@endphp