2013-10-17 95 views
3

传递数据在我的页面控制器我有无法从控制器到刀片模板laravel

$this->layout->content = View::make('authentication/login')->with('page_title','title'); 

我使用的是刀片文件我的模板。在HTML的头,我

<title>{{$page_title}}</title> 

我得到一个错误,$page_title是不确定的。

我最想要的是$data=array('page_title'=>'Login','second_item'=>'value')...。但是,由于我无法将变量的基本传递给一个视图,我首先坚持这一点。

回答

3

有很多方法来实现这一点,因为@Gravy指出,但她试图编写代码的方式来看,解决办法是:

$data = array(); 
$this->layout->with('data', $data); 
$this->layout->content = View::make('home'); 

见更多此处:http://forums.laravel.io/viewtopic.php?pid=58548#p58548

+0

这对我有用,谢谢。我尝试在('this-> data);'_construct'方法中添加'$ this-> layout->行,所以我不必在每个控制器中声明它,但是它返回了一个错误 - '用非对象'上的()调用成员函数。在单独的控制器功能里面,这很好。你知道它为什么不把它看作构造函数中的一个对象吗? – Nicola

+0

我想你可以使用View :: share()将数据从构造函数传递给视图。 – Navetz

2
$data = 
[ 
    'page_title' => 'Login', 
    'second_item' => 'value' 
    ... 
]; 

return View::make('authentication/login', $data); 

// or 

return View::make('authentication/login', compact('data')); 

// or 

return View::make('authentication/login')->with($data); 

// or 

return View::make('authentication/login')->with(['page_title' => 'Login', 'second_item' => 'value']); 

// or 

return View::make('authentication/login')->with(array('page_title' => 'Login', 'second_item' => 'value')); 
+1

返回查看:: make('authentication/login') - > with('data',$ data); – kaning

+1

您可以这样做@ kaning,但是您需要从$ data中访问视图内的所有元素。例如'{{$ data ['page_title']}}'。做我的第二个选项,你可以在视图内做这个'{{$ page_title}}' – Gravy

1
$data = array('page_title'=>'Login','second_item'=>'value'); 
return View::make('authentication/login', $data); 
0

因此,要获取控制器中的布局,您需要首先在布局刀片模板中声明变量content

在你的控制器中,你已经做了什么,但是在处理视图中的目录结构时记住点符号。 layouts.master与layouts/master.blade.php相同。

class UserController extends BaseController { 
    /** 
    * The layout that should be used for responses. 
    */ 
    protected $layout = 'layouts.master'; 

    public function getIndex() 
    { 
     // Remember dot notation when building views 
     $this->layout->content = View::make('authentication.login') 
            ->with('page_title','title'); 
    } 
} 

布局/ master.blade.php

<div class="content"> 
    {{-- This is the content variable used for the layout --}} 
    {{ $content }} 
</div> 

认证/ login.blade.php

<title>{{ $page_title }}</title> 

如果使用这种结构这将工作。

+0

我得到'$ content'变量回显正常。这是$ page_title,不回显。另外,为什么点符号而不是文件夹之间的'/'? – Nicola