วิธีใช้งาน Helper และ View สำหรับสร้าง Table by joeskb
Jan0
สำหรับการเขียนโปรแกรม Back-end บางทีก็ต้องชั่งน้ำหนักระหว่างภาษาว่าใช้ภาษาไหนมากกว่ากัน ซึ่งก็ขึ้นอยู่กับความถนัดของแต่ละคนด้วย
ตัวอย่างนี้แสดงให้เห็นวิธีใช้ Codeigniter helper และ View โดยเน้นไปทาง ฝั่ง CI มากกว่า HTML
$this->load->helper('html');
$this->load->helper('url');
$this->load->library('table');
$this->table->set_template(['table_open' => '<table border="1">"]);
$this->table->set_caption('News List');
$this->table->set_heading('Logo', 'Subject', 'Publish date');
foreach ($this->CI->db->get('news')->result_array() as $row) {
$this->table->add_row(empty($row['logo']) ? ' ' : img(base_url() . 'assets/images/default/news_logo/' . $row['logo']), $row['subject'], $row['publish_date']);
}
$data['news_list'] = $this->table->generate();
$this->load->view('master/news', $data);
อธิบายคำสั่งสำคัญได้ดังนี้ครับ
- $this->table->set_template ใช้สำหรับกำหนดลักษณะของตารางโดยใส่ config ต่างๆ เป็น array ลงไป
- $this->table->set_caption ใช้กำหนด caption ของตาราง ใส่ string ได้เลย
- $this->table->set_heading ใช้กำหนดหัวข้อของแต่ละคอลัมน์ ใส่ string คั่นด้วยลูกน้ำไปเรื่อยๆ ได้เลย
- $this->table->add_row เป็นการใส่ข้อมูลแต่ละแถว สามารถใช้วน loop ได้อย่างง่ายมาก
- $this->table->generate คำสั่งสำหรับสร้าง html ตามที่ได้ตั้งค่าไว้ที่ด้านบนแล้ว
-
ทางฝั่ง view ก็จะได้นำไปใช้งานง่ายๆ แบบนี้ครับ
<?= $news_list?>
Enjoy this article?
Consider subscribing to our RSS feed!
ไม่มีความเห็น
ยังไม่มีความเห็น