การติดตั้ง Smarty template engine

ก่อนที่จะติดตั้งได้เราก็ต้องไปดาวน์โหลดเอาไลบรารี่ของ Smarty ซะก่อนนะครับ หลังจากนั้นก็แตกไฟล์ที่ดาวน์โหลดมา โดยที่ไลบรารี่ที่เราจะใช้อยู่ใน Smarty-x.x.xx/libs เอาละครับเมื่อเตรียมไลบรารี่เสร็จแล้วก็มาเริ่มกันเลย

1. เราจะต้องก๊อปปี้ Smarty-x.x.xx/libs ไปไว้ใน public_html

/public_html/libs

2. ตัว Smarty ต้องการโฟลเดอร์หลัก ๆ อยู่ 4 โฟลเดอร์ด้วยกัน คือ templates,templates_c,configs และ cache โดยโฟลเดอร์เหล่านี้จะถูกเก็บไว้ภายใต้แอพลิเคชันของเรา เช่น ตัวอย่างนี้ ผมจะสร้างแอพลิเคชันที่มีชื่อว่า guestbook โครงสร้างของโฟลเดอร์ก็จะเป็น

/public_html/libs/Smarty.class.php
/public_html/libs/Smarty_Compiler.class.php
/public_html/libs/Config_File.class.php
/public_html/libs/debug.tpl
/public_html/libs/plugins/*.php

/public_html/guestbook/templates
/public_html/guestbook/templates_c
/public_html/guestbook/configs
/public_html/guestbook/cache

/public_html/guestbook/index.php

3. Smarty ต้องมีสิทธิ์ในการแก้ไขโฟลเดอร์ templates_c และ cache เราต้องแก้ permission ของโฟลเดอร์เหล่านี้ให้เป็น 770

4. สร้างไฟล์ index.tpl ไว้���ายในโฟลเดอร์ templates แก้ไขไฟล์ index.tpl เพื่อทดสอบการทำงาน โดยเพิ่มบรรทัดข้างล่างเข้าไป
ยินดีต้อนรับ, {$name}

5. แก้ไขไฟล์ index.php ดังนี้

//load Smarty library
require(‘../libs/Smarty.class.php’);$smarty = new Smarty;

$smarty->templates_dir = ‘templates/’;
$smarty->complie_dir = ‘templates_c/’;
$smarty->config_dir = ‘configs/’;
$smarty->cache_dir = ‘cache/’;

$smarty->assign(‘name’,’Mr.Smarty’);
$smarty->display(‘index.tpl’);

6. จากนั้นลองเปิดดูแอพลิเคชันของเรา http://www.example.com/guestbook/

7. ถ้าคุณเห็นข้อความว่า “ยินดีต้อนรับ, Mr.Smarty” ขี้นบนบราวเซอร์ก็แสดงว่าติดตั้งเสร็จเรียบร้อยครับ