Cakephp-view-elements

提供:Dev Guides
移動先:案内検索

CakePHP-ビュー要素

Webページの特定の部分は、複数のWebページで異なる場所に繰り返されます。 CakePHPは、これらの繰り返し部分を再利用するのに役立ちます。 これらの再利用可能な部分は、*要素-ヘルプボックス、追加メニュー*などと呼ばれます。 要素は基本的に*ミニビュー*です。 要素に変数を渡すこともできます。

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

上記の関数には3つの引数があります-

  • 最初の引数は、 /src/Template/Element/ フォルダー内のテンプレートファイルの名前です。
  • 2番目の引数は、レンダリングされたビューで使用可能にするデータの配列です。
  • 3番目の引数は、オプションの配列用です。 e.g. キャッシュ。

3つの引数のうち、最初の引数は必須ですが、残りはオプションです。

*helloworld.ctp* という名前の *src/Template/Element* ディレクトリに要素ファイルを作成します。 そのファイルに次のコードをコピーします。
*src/Template/Element/helloworld.ctp*
<p>Hello World</p>
*src/Template* に *Elems* フォルダーを作成し、そのディレクトリーの下に *index.ctp* という *View* ファイルを作成します。 そのファイルに次のコードをコピーします。
*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(){
      }
   }
?>

次のURLにアクセスして、上記の例を実行します。

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

出力

実行すると、上記のURLは次の出力を提供します。

ビュー要素