网页的某些部分会在多个网页上重复,但位于不同的位置. CakePHP可以帮助我们重复使用这些重复的部分.这些可重复使用的部件称为元素和减号;帮助框,额外菜单等.元素基本上是迷你视图.我们也可以在元素中传递变量.
Cake\View\View::element(string $elementPath, array $data, array $options =[])
上述函数有三个参数 :
第一个参数是/src/Template/Element/文件夹中模板文件的名称.
第二个参数是可用于渲染视图的数据数组.
第三个参数用于选项数组.例如缓存.
在3个参数中,第一个是强制性的,其余的是可选的.
在 src/Template/Element 目录中创建名为 helloworld.ctp 的元素文件.将以下代码复制到该文件中.
src/Template/Element/helloworld.ctp
<p>Hello World</p>
在 src/Template 创建文件夹 Elems 并在该目录下创建视图文件名为 index.ctp .将以下代码复制到该文件中.
src/Template/Elems/index.ctp
Element Example: <?php echo $this→element('helloworld'); ?>
在 config/routes.php 文件中进行更改,如以下程序所示.
config/routes.php
<?php use Cake\Core\Plugin; use Cake\Routing\RouteBuilder; use Cake\Routing\Router; Router::defaultRouteClass('DashedRoute'); Router::scope('/', function (RouteBuilder $routes) { $routes->connect('/elementexample',['controller'=>'Elems','action'=>'index']); $routes->fallbacks('DashedRoute'); }); Plugin::routes();
在 src/Controller/ElemsController.php 创建 ElemsController.php 文件.将以下代码复制到控制器文件中.
src/Controller/ElemsController.php
<?php namespace App\Controller; use App\Controller\AppController; use Cake\ORM\TableRegistry; use Cake\Datasource\ConnectionManager; class ElemsController extends AppController{ public function index(){ } } ?>
访问以下网址执行上述示例.
http://localhost:85/CakePHP/element-example
执行时,上面的URL会给你以下输出.