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

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

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


当前回答

我也遇到过类似的问题,并使用View composer找到了我认为正确的解决方案

视图编辑器允许你在每次调用某个视图时设置变量,这些变量可以是特定的视图,也可以是整个视图模板。不管怎样,我知道这不是对这个问题的直接回答(而且晚了2年),但它似乎是一个比在一个视图中使用blade设置变量更优雅的解决方案。

View::composer(array('AdminViewPath', 'LoginView/subview'), function($view) {
    $view->with(array('bodyClass' => 'admin'));
});

其他回答

最好练习在Controller中定义变量,然后使用compact()或->with()方法传递给视图。

否则,#TLGreg给出了最好的答案。

分配变量刀片模板,这里是解决方案

我们可以使用<?刀片页面中的PHP ?>标记

<?php $var = 'test'; ?>
{{ $var }

OR

我们可以用特殊的语法使用刀片注释

{{--*/ $var = 'test' /*--}}
{{ $var }}

至于我优雅的方式是这样的

{{ ''; $old_section = "whatever"; }}

然后回显$old_section变量。

{{ $old_section }}

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