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

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

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


当前回答

你可以使用我发布的软件包:https://github.com/sineld/bladeset

然后你可以轻松地设置你的变量:

@set('myVariable', $existing_variable)

// or

@set("myVariable", "Hello, World!")

其他回答

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

突然之间什么也不会出现。 根据我的经验,如果你必须做这样的事情,在模型的方法中准备html,或者在数组中重新组织你的代码。

永远不会只有一种方法。

{{ $x = 1 ? '' : '' }}

在laravel4中,您可以使用模板注释语法来定义/设置变量。

注释语法是{{——这里的任何东西都是Comment——}},它被blade引擎渲染为

<?PHP /* anything这里是comment */ ?>

比如,我们可以用它来定义变量

{{-- */$i=0;/* --}}

会被刀片渲染吗 < ?PHP /* */$i=0;/* */ ?>为我们设置变量。 无需更改任何代码行。

在Laravel 5.1、5.2中:

https://laravel.com/docs/5.2/views#sharing-data-with-all-views

您可能需要与应用程序呈现的所有视图共享一段数据。你可以使用视图工厂的share方法。通常,您应该在服务提供者的引导方法中放置共享调用。您可以自由地将它们添加到AppServiceProvider或生成一个单独的服务提供者来容纳它们。

编辑文件:/app/Providers/AppServiceProvider.php

<?php

namespace App\Providers;

class AppServiceProvider extends ServiceProvider
{        
    public function boot()
    {
        view()->share('key', 'value');
    }

    public function register()
    {
        // ...
    }
}

同样的问题也困扰着我。但我能够通过使用以下代码段来管理这个问题。在你的刀片模板中使用这个。

<input type="hidden" value="{{$old_section = "whatever" }}">

{{$old_section }}