cakephp 3.0.x 扩展视图?
cakephp 3.0.x extending view?
我正在使用 cakephp 3.0.x,我想创建一个包含多个视图的页面。例如。如果我从其他模板中获得这些 index.ctp,如下所示
- Template/Customers/index.ctp
- Template/Orders/index.ctp
我想让一个页面说 Template/Main/index.ctp。其中包含来自 Customers 和 Orders 的 index.ctp。本质上,视图中的视图(view-ception :P)。这可能吗?如果可以,怎么做?
是的,如果您使用 View Elements 就可以做到这一点。
最好的方法是为客户索引模板创建一个元素模板,然后在您的 Customers/index 和 Main/index 模板中输出它,如下所示:-
// Output Template/Element/customers.ctp
echo $this->Element('customers');
元素模板将从调用模板继承变量,但您也可以将变量传递给它。例如,如果您需要一个 $data
变量,但在您的控制器中将其设置为 $customers
:-
echo $this->Element('customers', ['data' => $customers]);
如果您不想创建一个实际的元素视图模板,您只想按原样重用现有的 Customers/index 模板,您仍然可以在 Main/index 模板中使用 $this->Element()
输出它:-
// Output Template/Customers/index.ctp
echo $this->Element('../Customers/index');
就我个人而言,我会避免这样做并选择第一个示例并修改您现有的 Customers/index 以使用元素,因为这将使代码在未来更易于维护。
我正在使用 cakephp 3.0.x,我想创建一个包含多个视图的页面。例如。如果我从其他模板中获得这些 index.ctp,如下所示
- Template/Customers/index.ctp
- Template/Orders/index.ctp
我想让一个页面说 Template/Main/index.ctp。其中包含来自 Customers 和 Orders 的 index.ctp。本质上,视图中的视图(view-ception :P)。这可能吗?如果可以,怎么做?
是的,如果您使用 View Elements 就可以做到这一点。
最好的方法是为客户索引模板创建一个元素模板,然后在您的 Customers/index 和 Main/index 模板中输出它,如下所示:-
// Output Template/Element/customers.ctp
echo $this->Element('customers');
元素模板将从调用模板继承变量,但您也可以将变量传递给它。例如,如果您需要一个 $data
变量,但在您的控制器中将其设置为 $customers
:-
echo $this->Element('customers', ['data' => $customers]);
如果您不想创建一个实际的元素视图模板,您只想按原样重用现有的 Customers/index 模板,您仍然可以在 Main/index 模板中使用 $this->Element()
输出它:-
// Output Template/Customers/index.ctp
echo $this->Element('../Customers/index');
就我个人而言,我会避免这样做并选择第一个示例并修改您现有的 Customers/index 以使用元素,因为这将使代码在未来更易于维护。