CakePHP - 擴充套件檢視



很多時候,在製作網頁時,我們希望在其他頁面中重複頁面的某些部分。CakePHP 提供了這樣的功能,可以將一個檢視擴充套件到另一個檢視中,這樣就無需重複程式碼。

extend() 方法用於在View 檔案中擴充套件檢視。此方法接受一個引數,即帶有路徑的檢視檔名。提供檢視檔名時,請勿使用副檔名 .ctp。

示例

按照以下程式所示修改 config/routes.php 檔案。

config/routes.php

<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
   $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
      'httpOnly' => true,
   ]));
   $builder->applyMiddleware('csrf');
   $builder->connect('extend',['controller'=>'Extends','action'=>'index']);
   $builder->fallbacks();
});

src/Controller/目錄下建立一個名為ExtendsController.php的檔案。將以下程式碼複製到控制器檔案中。

src/Controller/ExtendsController.php

<?php
   namespace App\Controller;
   use App\Controller\AppController;
   class ExtendsController extends AppController{
      public function index(){
      }
   }
?>

src/Template目錄下建立一個名為Extends的目錄,並在該目錄下建立一個名為header.php的View檔案。將以下程式碼複製到該檔案中。

src/Template/Extends/header.php

<div align="center">
   <h1>Common Header</h1>
</div>
<?= $this->fetch('content') ?>

Extends目錄下建立另一個名為index.phpView檔案。將以下程式碼複製到該檔案中。在這裡,我們正在擴充套件上面的檢視header.php

src/Template/Extends/index.php

<?php $this->extend('header'); ?>
This is an example of extending view.

訪問以下 URL https:///cakephp4/extend 來執行上述示例。

輸出

執行後,您將收到以下輸出。

Common Header
廣告
© . All rights reserved.