从视图中的助手文件访问变量-Laravel 4.2


Accessing variable from helpers file in views - Laravel 4.2

我在/app文件夹中创建了一个助手文件,其中包含以下内容:

$constants = DB::table('constants')->get();
foreach ($constants as $constant) {
    $C[$constant->type] = $constant->value;
}
echo $C['business_name'];

这是有效的,但如果我尝试

echo $C['business_name'];

在我的一个视图中,我得到了一个未定义的$C错误。我已经将助手文件添加到我的启动/全局文件中,我知道它有效。。。

我应该采取哪些步骤在视图中使用此变量?

您需要通过View::makeView::make('someBlade')->with(data); 的第二个参数将数据直接传递到视图中

所以在你的情况下,可能是这样的:View::make('someBlade', $C);

如果你真的非常想要全局变量,你可以对视图执行以下操作:View::share('c', $C);

http://laravel.com/docs/4.2/responses

我认为您需要在helper中创建一个函数,并在视图中调用该函数。它将自动显示这个变量的值,但您需要更改";回声;用";返回";在函数的最后一行。

function xyz()
{
$constants = DB::table('constants')->get();
foreach ($constants as $constant) {
    $C[$constant->type] = $constant->value;
}
return $C['business_name'];
}
Call this function in your view like this. {{xyz()}}

如果您返回数组{?$abc=xyz();?}使blade filter不回显值,请将此函数传递给数组变量,并显示如下{{$abc['business_name']}}