วันศุกร์ที่ 18 กันยายน พ.ศ. 2552

ติดตั้ง Smarty Template Engine

Smarty Template Engine เป็นชุด Class Library ที่สร้างขึ้น เพื่อมาจัดการส่วนการแสดงผล  หรือ Presentation Layer หรือ Views ใน MVC ที่มีประสิทธิภาพยอดเยี่ยม และใช้งานง่าย


ทำไมถึงใช้ smarty?

  • smarty จะแยกการ coding ออกจาก design เพราะ designer บางท่านอาจจะงง ๆ กับการ coding
  • smarty สร้างมุมมอง MVC ให้แก่ PHP เพราะ smarty อยู่ในกลุ่ม view
  • smarty ช่วยให้โปรแกรมเมอร์ลืมคำว่า “เขาบอกให้แก้ code ตรงนั้น คุณไปแก้ template ทำไม” (พยายามหาคำสุภาพมาเผยแพร่)

วิธีใช้งาน

  1. อันดับแรก ไปโหลด library มาก่อน จาก Web page ของ Smarty ก็คือ http://www.smarty.net
  2. ต่อไปก็ unzip แล้วไปวางไว้ใน path ของเว็บที่จะใช้งาน smarty
  3. ทดสอบ และใช้งานจริง

วิธีการทดสอบ

File PHP = test.php

01.<?
02.require_once('library/smarty/Smarty.class.php');  // อันนี้คงรู้ ถ้าไม่รู้อย่าใช้เลย smarty เดี๋ยวมันจะงงไปใหญ่
03.  
04.$smarty = new Smarty();
05.  
06.$smarty->template_dir   = 'templates';
07.// ที่อยู่ของ template ของเรา
08.  
09.$smarty->compile_dir    = 'templates_c';
10.// smarty จะทำการ complie code เรา ดังนั้นเราจะต้องระบุบ path ที่เก็บ file complie แล้ว
11.  
12.$smarty->assign('hello', 'สวัสดี'); // ใส่ค่าแนบลงไป
13.$name = array('eXscript','Phun','Soloman');
14.$smarty->assign('name',$name); // กำหนดค่า variable 2 เป็น array
15.$smarty->assign('title','สวัสดีทุกคน'); // กำหนดค่า variable 3
16.  
17.$smarty->display('good.tpl'); // ให้แสดงผลโดยใช้ template อะไร
18.?>

File TPL = templates/good.tpl

01.<html>
02.<head>
03.<title>{$title}</title>
04.</head>
05.<body>
06.{foreach from=$name item=displayname}
07.{$hello} {$displayname}<br />
08.{/foreach}
09.</body>
10.</html>

ผลลัพธ์

สวัสดี eXscript
สวัสดี Phun
สวัสดี Soloman

และชื่อ title bar จะเขียนว่า “สวัสดีทุกคน”

แท็ก Technorati ,


ไม่มีความคิดเห็น: