View layout trong CodeIgniter

View layout giúp tạo ra các page layout cho website. Bạn có thể tạo các layout khác nhau: 1 cột, 2 cột …

Cách tạo 1 layout:

Layout là 1 file view mà trong đó sử dụng phương thức renderSection(). Ví dụ:

File app\Views\default.php:

PHP
<!doctype html>
<html>
<head>
    <title>My Layout</title>
</head>
<body>
    <?= $this->renderSection('content') ?>
</body>
</html>

Hàm renderSection() chỉ có 1 tham số là tên của section.

Muốn chèn view vào layout, sử dụng hàm extend() ở đầu file:

PHP
<?= $this->extend('default') ?>

Phương thức extend() lấy tên của bất kỳ file view nào bạn muốn sử dụng. Mặc định nó sẽ lấy trong thư mục View. Nếu bạn muốn include namespace:

PHP
<?= $this->extend('Blog\Views\default') ?>

Tất cả content trong view mà extend 1 layout phải được bao gồm trong section($name)endSection(). Ví dụ:

File app\Views\some_view.php:

PHP
<?= $this->extend('default') ?>

<?= $this->section('content') ?>
    <h1>Hello World!</h1>
<?= $this->endSection() ?>

Hàm endSection() không cần tên section, nó tự động biết cái nào cần đóng.

Section có thể bao gồm section lồng vào nhau:

PHP
<?= $this->extend('default') ?>

<?= $this->section('content') ?>
    <h1>Hello World!</h1>
    <?= $this->section('javascript') ?>
       let a = 'a';
    <?= $this->endSection() ?>
<?= $this->endSection() ?>

Render ra view:

Trong controller gọi view như bình thường:

PHP
<?php

namespace App\Controllers;

class MyController extends BaseController
{
    public function index()
    {
        return view('some_view');
    }
}

Include 1 view con:

Sử dụng $this->include() để include 1 view con ví dụ như header, footer, sidebar:

PHP
<?= $this->extend('default') ?>

<?= $this->section('content') ?>
    <h1>Hello World!</h1>

    <?= $this->include('sidebar') ?>
<?= $this->endSection() ?>

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *