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

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

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


当前回答

你会把事情搞得太复杂了。

使用纯php

<?php $i = 1; ?>
{{$i}}

donesies。

(或者https://github.com/alexdover/blade-set看起来也很简单)

我们都是通过在视图中设置变量来“入侵”系统,所以为什么要让“入侵”变得更复杂呢?

在Laravel 4中测试。

另一个好处是语法高亮显示工作正常(我以前使用注释黑客,它是可怕的阅读)

其他回答

在拉拉维尔8

@php

 $name="Abdul mateen";

{{ echo $name; }}
    
@endphp

您可以使用如下所示的extend方法来扩展刀片。

Blade::extend(function($value) {
    return preg_replace('/\@var(.+)/', '<?php ${1}; ?>', $value);
});

在此之后,按如下方式初始化变量。

@var $var = "var"

拉拉维尔 7 :

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

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

我不认为你可以——但是,这种逻辑可能应该在你的控制器中处理,并传递到已经设置好的视图中。