CakePHP - 檢視元素



網頁的某些部分在多個網頁上重複出現,但位置不同。CakePHP 可以幫助我們重用這些重複的部分。這些可重用的部分稱為元素 - 幫助框、額外選單等。元素基本上是一個迷你檢視。我們也可以在元素中傳遞變數。

Cake\View\View::element(string $elementPath, array $data, array $options =[]

上述函式有三個引數,如下所示:

  • 第一個引數是/src/Template/element/資料夾中模板檔案的名稱。

  • 第二個引數是要提供給渲染檢視的資料陣列。

  • 第三個引數用於選項陣列,例如快取。

在 3 個引數中,第一個是必須的,其餘是可選的。

示例

src/Template/element目錄下建立一個名為helloworld.php的元素檔案。將以下程式碼複製到該檔案中。

src/Template/element/helloworld.php

<p>Hello World</p>

src/Template下建立一個名為Elems的資料夾,並在該目錄下建立一個名為index.php的檢視檔案。將以下程式碼複製到該檔案中。

src/Template/Elems/index.php

Element Example: <?php echo $this->element('helloworld'); ?>

如以下程式所示,對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('/element-example',['controller'=>'Elems','action'=>'index']);
   $builder->fallbacks();
});

src/Controller/ElemsController.php處建立一個ElemsController.php檔案。將以下程式碼複製到控制器檔案中。

src/Controller/ElemsController.php

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

透過訪問以下 URL https:///cakephp4/element-example 執行上述示例

輸出

執行後,上述 URL 將為您提供以下輸出。

Element Example
廣告

© . All rights reserved.