很多時(shí)候,當(dāng)制作網(wǎng)頁時(shí),我們想在網(wǎng)頁頁面重復(fù)另一網(wǎng)頁的某些部分。 CakePHP能實(shí)現(xiàn)從一個(gè)視圖繼承一個(gè)視圖,因此,我們不必再重復(fù)寫代碼。extend()方法用于在視圖文件中繼承視圖。這個(gè)方法需要一個(gè)參數(shù),帶文件路徑的視圖文件名,但不必帶擴(kuò)展名.ctp。
在以下項(xiàng)目中,修改如下所示config/routes.php文件。
config/routes.php
<?php use CakeCorePlugin; use CakeRoutingRouteBuilder; use CakeRoutingRouter; Router::defaultRouteClass('DashedRoute'); Router::scope('/', function (RouteBuilder $routes) { $routes->connect('extend',['controller'=>'Extends','action'=>'index']); $routes->fallbacks('DashedRoute'); }); Plugin::routes();
在src/Controller/下創(chuàng)建ExtendsController.php文件。復(fù)制以下代碼至其中。
src/Controller/ExtendsController.php
<?php namespace AppController; use AppControllerAppController; class ExtendsController extends AppController{ public function index(){ } } ?>
在src/Template目錄下創(chuàng)建一個(gè)名為Extends的文件夾,并在Extends文件夾下創(chuàng)建一個(gè)名為header.ctp的視圖文件。復(fù)制以下代碼至其中。
src/Template/Extends/header.ctp
<div align = "center"><h1>Common Header</h1></div> <?= $this->fetch('content') ?>
在Extends目錄下創(chuàng)建另一個(gè)視圖文件index.ctp。復(fù)制以下代碼至其中。在這里,我們繼承了header.ctp。
src/Template/Extends/index.ctp
<?php $this->extend('header'); ?> This is an example of extending view.
通過訪問以下網(wǎng)址執(zhí)行上面的例子。
http://localhost:85/CakePHP/extend
執(zhí)行以上程序,您會(huì)看到以下頁面。
更多建議: