2017-09-06 68 views
0

我問的問題非常相似,並且已經提出了問題。但它對我有用。Cakephp 2.9將控制器中的變量傳遞給佈局查看

ViewReportsController.php

class ViewReportsController extends AppController { 
public function index() { 
$count_table = 10;//sample variable that is available in view 
$this->set('count_tablen',$count_table); 
} 
} 

APP /瀏覽/設計/ default.thtml中

pr($count_tablen); 

現在我得到的錯誤says-未定義的變量:count_tablen [APP /瀏覽/設計/默認.ctp,line 228]

+0

您打哪個網址?該變量僅爲index.ctp定義。 –

回答

2

您在主佈局模板中使用了一個可能被多個控制器操作使用的變量。因此,您提供的代碼示例僅適用於/view_reports/index。如果你想設置的變量中,你需要做到這一點的beforeRender回調AppController佈局模板中使用,以便它可以在任何地方使用: -

public function beforeRender() { 
    parent::beforeRender(); 
    $count_table = 10; 
    $this->set('count_tablen', $count_table); 
} 

如果使用多個佈局模板,您可以檢查哪些模板將在設置變量之前用於beforeRender: -

public function beforeRender() { 
    parent::beforeRender(); 
    if ($this->layout === 'default') { 
     $count_table = 10; 
     $this->set('count_tablen', $count_table); 
    } 
} 
+1

非常感謝,我學到了一些新東西。它工作得很好 – Manasa

相關問題