การใช้งาน smarty เบื่้องต้นเพื่อทำเทมเพลตเว็บไซต์

หมวดสำหรับแบ่งบันความ รู้ต่างๆ จะมีหมวดย่อยๆ ในหมวดนี้ เช่น php, SQL, XML, CSS

Moderator: mindphp, ผู้ดูแลกระดาน

ภาพประจำตัวสมาชิก
tiamkeaw
PHP Sr. Member
PHP Sr. Member
โพสต์: 81
ลงทะเบียนเมื่อ: 01/01/1970 7:00 am

การใช้งาน smarty เบื่้องต้นเพื่อทำเทมเพลตเว็บไซต์

โพสต์ที่ยังไม่ได้อ่าน โดย tiamkeaw »

1. สร้างโฟลเดอร์ชื่อ myhome ใน htdocs
2. ดาว์นโหลด Smarty ในบทความนี้จะใช้เวอร์ชั่น 2.6.27 โหลด
3. แตกไฟล์ที่โหลดมาไว้ที่ htdocs/myhome
4. สร้างโฟลเดอร์ที่ต้องใช้กับ smarty
- myhome/templates
- myhome/templates_c
- myhome/configs
- myhome/cache
templates_c และ cache ต้องตั้ง permission 777

5. สร้างไฟล์แรก setup.php

โค้ด: เลือกทั้งหมด

<?php
// myhome/setup.php
require_once( "../../Smarty-2.6.27/libs/Smarty.class.php" ); // นำเข้า smarty class

class Smarty_MyHome extends Smarty
{
   function Smarty_MyHome()
   {
       /* กำหนดพาธ 4 diretory ที่ต้องใช้ */
        $this->Smarty();
        $this->template_dir = dirname( __FILE__ ) . "/templates/";
        $this->compile_dir = dirname( __FILE__ ) . "/templates_c/";
        $this->config_dir = dirname( __FILE__ ) . "/configs/";
        $this->cache_dir = dirname( __FILE__ ) . "/cache/";

        $this->caching = true; // เปิดการใช้งาน cach
        
        /* การส่งค่าไปแสดงใน layout */
        $this->assign( "title", "ก้าวแรกสู่ Smarty 2.6.27" ); // การกำหนดค่าแบบ string
        
        $arr["head"] = "My Home";  // การกำหนดค่าแบบ array
        $arr["content"] = "Wellcome to my home."; 
        $this->assign( "arr", $arr );
   }

}
?>
6. สร้างไฟล์ myhome/htdocs/index.php เพื่อเรียกใช้งาน class "Smarty_MyHome"

โค้ด: เลือกทั้งหมด

<?php
// myhome/htdocs/index.php
require( "../setup.php" ); // นำเข้าไฟล์ setup.php 

$smarty = new Smarty_MyHome(); // สร้าง class

$smarty->assign( "name", "Ned" ); // การส่งค่าเพื่อนำไปใช้ใน layout

$smarty->display( "index.tpl" ); // เรียกใช้ layout
?>
7. สร้างไฟล์ myhome/templates/index.tpl

โค้ด: เลือกทั้งหมด

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>{$title} - Smarty</title> <!-- {$title} การแสดงค่าแบบ string ที่กำหนดมาจาก setup.php -->
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </head>
    <body>
        <h1>{$arr.head}</h1> <!-- {$arr.head} การแสดงค่าแบบ array ที่กำหนดมาจาก setup.php -->
        <div>{$arr.content}</div>
    </body>
</html>
สามารถดูการกำหนดชนิดของตัวแปรต่างได้ที่ลิ้งค์นี้
http://www.smarty.net/docsv2/en/languag ... iables.tpl
แนบไฟล์
smarty.rar
(176.07 KiB) ดาวน์โหลดแล้ว 239 ครั้ง
  • Similar Topics
    ตอบกลับ
    แสดง
    โพสต์ล่าสุด

ผู้ใช้งานขณะนี้

สมาชิกกำลังดูบอร์ดนี้: facebook.com [Crawler] และบุคลทั่วไป 58