CakePHP的視圖元素

2018-01-14 12:41 更新

多個網(wǎng)頁在不同的位置重復(fù)引用某些特定的部分。 CakePHP可以幫助我們重用這些重復(fù)的部分。這些可重用部件稱為元素-幫助框,額外菜單等;元素是一個迷你視圖 ,我們可以在元素中傳遞變量。

CakeViewView::element(string $elementPath, array $data, array $options =[])

上面的函數(shù)有三個參數(shù) -

  • 第一個參數(shù)是在/src/Template/Element/文件夾中的模板文件的名稱。

  • 第二個參數(shù)是渲染視圖所用用到的可用數(shù)據(jù)的數(shù)組。

  • 第三個參數(shù)是可選項的數(shù)組。例如緩存。

在此3個參數(shù)中,第一個是必須的,其余的都是可選的。

src/Template/Element目錄中創(chuàng)建名為helloworld.ctp 的的元素文件。復(fù)制以下代碼至其中。

src/Template/Element/helloworld.ctp

<p>Hello World</p>

src/Template目錄下創(chuàng)建一個名為Elems的文件夾,并在此Elems目錄下創(chuàng)建一個名為index.ctp視圖文件。復(fù)制以下代碼至其中。

src/Template/Elems/index.ctp

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

在以下項目中,修改config/routes.php文件。

config/routes.php文件

<?php
   use CakeCorePlugin;
   use CakeRoutingRouteBuilder;
   use CakeRoutingRouter;

   Router::defaultRouteClass('DashedRoute');
   Router::scope('/', function (RouteBuilder $routes) {
      $routes->connect('/elementexample',['controller'=>'Elems','action'=>'index']);
      $routes->fallbacks('DashedRoute');
   });
   Plugin::routes();

src/Controller/下創(chuàng)建ElemsController.php文件。復(fù)制以下代碼至其中。

src/Controller/ElemsController.php

<?php
   namespace AppController;
   use AppControllerAppController; 
   use CakeORMTableRegistry;
   use CakeDatasourceConnectionManager;

   class ElemsController extends AppController{
      public function index(){
      }
   }
?>

通過訪問以下網(wǎng)址執(zhí)行上面的例子。

http://localhost:85/CakePHP/element-example

輸出

執(zhí)行以上程序,您會看到以下頁面。



以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號