CodeIgniter 視圖層純 PHP,直接使用 foreach 遍歷控制器傳遞的陣列。本文示範控制器準備數據、視圖渲染列表、表格、巢狀結構的常見模式。
<?php
class Tasks extends CI_Controller {
public function index() {
$this->load->model('TaskModel');
$data['tasks'] = $this->TaskModel->getAll(); // 返回陣列
$data['page_title'] = '任務列表';
$this->load->view('templates/header', $data);
$this->load->view('tasks/index', $data);
$this->load->view('templates/footer');
}
}
?>
<!-- views/tasks/index.php -->
<h1><?= $page_title ?></h1>
<ul class="task-list">
<?php foreach ($tasks as $task): ?>
<li>
<strong><?= html_escape($task['title']) ?></strong>
<span class="status <?= $task['completed'] ? 'done' : 'pending' ?>">
<?= $task['completed'] ? '已完成' : '進行中' ?>
</span>
</li>
<?php endforeach; ?>
</ul>
<table class="table">
<thead>
<tr>
<th>ID</th><th>標題</th><th>負責人</th><th>截止日期</th><th>狀態</th><th>操作</th>
</tr>
</thead>
<tbody>
<?php foreach ($tasks as $task): ?>
<tr>
<td><?= $task['id'] ?></td>
<td><?= html_escape($task['title']) ?></td>
<td><?= html_escape($task['assignee'] ?? '未指派') ?></td>
<td><?= date('Y-m-d', strtotime($task['due_date'])) ?></td>
<td>
<span class="badge <?= $task['status'] ?>">
<?= $this->statusLabels[$task['status']] ?? $task['status'] ?>
</span>
</td>
<td>
<a href="<?= site_url('tasks/edit/' . $task['id']) ?>">編輯</a> |
<a href="<?= site_url('tasks/delete/' . $task['id']) ?>" onclick="return confirm('確定刪除?')">刪除</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php
// 控制器傳遞樹形陣列
$data['categories'] = $this->CategoryModel->getTree(); // 含 children 遞歸結構
?>
<!-- 視圖遞歸片段 views/categories/_tree.php -->
<ul class="category-tree">
<?php foreach ($categories as $cat): ?>
<li>
<span class="toggle"></span>
<a href="<?= site_url('categories/edit/' . $cat['id']) ?>">
<?= html_escape($cat['name']) ?>
</a>
<?php if (!empty($cat['children'])): ?>
<?php $this->load->view('categories/_tree', ['categories' => $cat['children']]); ?>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
永遠使用 html_escape() (CI3) 或 esc() (CI4) 輸出用戶數據,防止 XSS:
<?= html_escape($task['title']) ?> <!-- CI3 -->
<?= esc($task['title']) ?> <!-- CI4 -->
<?php if (empty($tasks)): ?>
<div class="alert alert-info">暫無任務,<a href="<?= site_url('tasks/create') ?>">新增第一個</a></div>
<?php else: ?>
<!-- 正常渲染列表 -->
<?php endif; ?>
<?php
// 控制器
$config['base_url'] = site_url('tasks/index');
$config['total_rows'] = $this->TaskModel->countAll();
$config['per_page'] = 15;
$this->pagination->initialize($config);
$data['tasks'] = $this->TaskModel->getPaginated($config['per_page'], $this->uri->segment(3));
$data['pagination'] = $this->pagination->create_links();
$this->load->view('tasks/index', $data);
?>
<!-- 視圖 -->
<?= $pagination ?>