當建立好 Controller 後,便可來了解該如何使用視圖來製作樣板以及將資料帶入。

首先如果我們有以下的 Controller,便可以使用 view 而非直接在 Controller 內 echo HTML 的內容,可以參考以下的寫法讀入 view:

class Store extends Controller
{
    public function index()
        {
            return view('home');
        }
}

 

此時讀到此頁面,便會去讀取  app/Views/home.php 的內容,我們也可以透過 Controller 將變數帶入 view 已根據不同情況顯示不同的內容:

public function index()
        {
            $data=[
                "title" => "我是標題"
            ];
            return view('home', $data);
        }

 

這時在 home.php 裡便可透過變數顯示內容:

<title><?= $title ?></title>

 

在 CodeIgniter 4 之後也跟許多其他的框架一樣,可以使用 extend 的方式去套用樣板,比如說我設定一個樣板名為 layout.php 長得這樣:

<!doctype html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title><?= $title ?></title>
</head>
<body>
<?= $this->renderSection('content') ?>

</body>
</html>

 

我在 home.php 那邊如果想要使用這個樣板,就可以這樣寫:

<?= $this->extend('layout') ?>

<?= $this->section('content') ?>
    <h1><?= $title ?></h1>
<?= $this->endSection() ?>

這樣就可以使用 layout 的樣版,而 home.php 這一頁不一樣的地方則可以寫在 $this->section('content') 的區段之內。

$this->renderSection() 也可以設定很多個區塊,可以依據需求設定在這些區塊內寫入不同的內容。

以上為 CodeIgniter 4 視圖(view)的基本參考用法。