ข้ามไปที่เนื้อหาหลัก

สอนเขียน PHP ตอน JavaScript Template Engine แบบง่ายๆ

 
PHP javascript template engine

โครงสร้างของไฟล์

- tpng.js
- jsDemo.php
------ view/tpl_template.html




[ HTML template ]

<h3>{blog_heading}</h3>
<table class="table table-bordered">
    <tr>
        <th>ID</th>
        <th>Label</th>
    </tr>
{blog_entries}
    <tr>
        <td>{id}</td>
        <td>{title}</td>
    </tr>
{/blog_entries}
</table>

[ PHP main page ]

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
   
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>ทดสอบ JavaScript Template Engine</title>

    <!-- Bootstrap -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
   
  </head>
  <body>
    <h1>ทดสอบการใช้งาน JavaScript Template Engine!</h1>
   
    <div id="content"></div>

    <!-- jQuery -->
    <script src="js/jquery.min.js"></script>
    <!-- Bootstrap -->
    <script src="js/bootstrap.min.js"></script>
   
    <?php
        $data = array(
  array('id' => '1','title' => 'วัดพระแก้ว','detail' => 'ตัวเมืองเชียงราย'),
  array('id' => '2','title' => ' ร้านกาแฟ Singha Park Café ','detail' => 'มหาวิทยาลัยแม่ฟ้าหลวง'),
  array('id' => '3','title' => 'จุดชมวิว 360 องศา @วัดดอยกองข้าว','detail' => 'บ้านฮ่องอ้อ ตำบลดอยฮาง อำเภอเมืองเชียงราย'),
  array('id' => '4','title' => 'ล่องแพ หนองบัวหลวง','detail' => 'เส้นทางเชียงราย - แม่จัน – เชียงแสน'),
  array('id' => '5','title' => 'บ้านกะเหรี่ยงรวมมิตร..','detail' => 'ตำบลแม่ยาว ระยางทางประมาณ 7 กม'),
  array('id' => '6','title' => 'พิพิธภัณฑ์ลื้อลายคำ','detail' => 'บ้านศรีดอนชัย อ.เชียงของ จ.เชียงราย '),
  array('id' => '7','title' => 'ถนนคนเดินเชียงราย','detail' => 'อยู่ใจกลางเมืองเชียงราย')
);

    ?>
   
    <script src="tpng.js"></script>
    <script>
        jsTPNG.tp_data = {
    "blog_heading": "ทดสอบสร้างตาราง",
    "blog_entries": <?php echo json_encode($data);?>
};
        jsTPNG.loadView('tpl_test.html');
        jsTPNG.render('#content');
    </script>
   
  </body>
</html>

[ tpng.js ]

/* 
* -- Songchai @ June 2016
* -- สำหรับเขียนแยกการทำงานระหว่าง PHP กับ HTML 
* -- PHP ใช้รับส่งข้อมูล ส่วนการแสดงผล ยกให้ JavaScript 
*/
var jsTPNG = {
    tp_data : '',
    tpl_content : '',
    view_directory : 'view/',
   
    loadView : function(file_name) {
        var tpl_view;
        $.ajax({
            type: "GET",
            url: this.view_directory + file_name,
            dataType: "text",
            async : false, //synchronous requests
            success : function(data){tpl_view = data;}
        });
        this.tpl_content = tpl_view;
    },
   
    /*** Matching & Replace ***/
    matchArray : function(text, xDataArray, mKey) {
        var str = text;
        var regex = /{(.+?)}/g;
        $.each( xDataArray, function( key, value ){
            if(mKey){
                str = str.replace("{"+ mKey +"}", "").replace("{/"+ mKey +"}", "");
            }
            if(typeof value == 'object'){
                text += jsTPNG.matchArray(str, value);
            }else{
                text = str.replace(regex, function($0, $1){return xDataArray[$1];});
            }
        });
        return text;
    },
   
    render : function(target_elm) {
        var x_data = jsTPNG.tp_data;
        if(x_data == undefined){
            alert('จะต้องส่งข้อมูลอาร์เรย์แบบ JSON เข้ามาในฟังก์ชั่น render() ด้วยครับ');
            console.log('jsTPNG.tp_data = JSON_DATS');
            return;
        }
        var result = this.tpl_content;
        $.each( x_data, function( key, value ) {
            if($.isArray(value)){
                var patt = '/{'+key+'}([\\S\\s]*){\\/'+key+'}/g';// key
                var patt = eval(patt);
                var text_array = result.match(patt);//array
                if(text_array != null){
                    var textList = jsTPNG.matchArray(text_array[0], value, key);
                    textList = textList.replace(text_array[0], '');
                    result = result.replace(text_array[0], textList);
                }
            }else{
                result = result.replace(eval('/{' + key + '}/g'), value);
            }
        });
        if(target_elm != undefined){
            $(target_elm).html(result);
        }else{
            return result;
        }
    }
}

ความคิดเห็น

โพสต์ยอดนิยมจากบล็อกนี้

แจกฟรี!! ระบบต่างๆที่พัฒนาด้วย PHP สำหรับนำไปใช้ในงานต่างๆ

       สำหรับหลายท่านที่ขอโค้ดเข้ามาทาง Inbox ของเฟซบุ๊กแฟนเพจ หรือถามถึงระบบต่างๆหลังไมค์มานั้น ส่วนใหญ่ก็มีแจกอยู่แล้วในเว็บบอร์ด ThaiCreate.Com นะครับ และด้านล่างนี้ก็เป็นระบบต่างๆที่แจกให้นำไปลองใช้ลองศึกษากันครับ

สอนเขียน PHP แสดงการจองห้องประชุมแบบไฮไลท์ตามช่วงเวลา (แบบเชื่อมต่อฐานข้อมูล MySQL)

ตัวอย่าง ผลลัพธ์ที่ได้จากการจองในฐานข้อมูล ตาราง tb_room สร้างตารางรายชื่อห้องประชุม สำหรับ id นั้นเป็น Primarykey จะกำหนดให้สร้างอัตโนมัติ ทุกครั้งที่เราเพิ่มชื่อห้องประชุมใหม่ -- -- Database: `tobedev_example` -- -- -------------------------------------------------------- -- -- Table structure for table `tb_room` -- CREATE TABLE IF NOT EXISTS `tb_room` (   `id` int(11) NOT NULL,   `name` varchar(30) NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; -- -- Dumping data for table `tb_room` -- INSERT INTO `tb_room` (`id`, `name`) VALUES (1, 'ห้องประชุม 1'), (2, 'ห้องประชุม 2'), (3, 'ห้องประชุม 3'), (4, 'ห้องประชุม 4'), (5, 'ห้องประชุม 5'); -- -- Indexes for dumped tables -- -- -- Indexes for table `tb_room` -- ALTER TABLE `tb_room`   ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `tb_room` -- ALTER TABLE `tb_room`   MODIFY `i...

การนำไอคอน มาแสดงบน Fullcalendar

เนื่องจากมีน้องคนหนึ่งให้ช่วยดูโค้ดเกี่ยวกับ Fullcalendar ให้หน่อย แล้วพอดีช่วงนี้ผมก็กำลังสนใจปฏิทิน Fullcalendar อยู่พอดี จึงลองหาสาเหตุที่ไม่สามารถแสดงข้อมูลจาก MySQL และไม่สามารถแทรก icon เข้าไปใน Fullcalendar ได้ จากที่สังเกตุได้ครั้งแรกคือ Error ที่ Console ของ Firefox เกี่ยวกับฟังก์ชั่นที่เขียนผิด และก็มีการ echo ค้างไว้ในส่วนของไฟล์ getCalendar.php ก็เลยจัดการทดสอบแล้วลบ echo ออกให้เหลือแค่ echo json_encode($event_array); ที่ได้ใช้งานจริงเท่านั้น ขั้นตอนการตรวจสอบความถูกต้องของโค้ด PHP 1) ต้องแน่ใจว่าคำสั่งที่เขียนไว้ สามารถดึงข้อมูลมาแสดงผลได้ด้วยการ echo $sql; 2) นำคำสั่งที่ได้ไปรันในโปรแกรมจัดการฐานข้อมูล ในที่นี้คือ phpMyAdmin 3) เมื่อตรวจสอบดูผลลัพธ์ที่ได้ หากถูกต้องมีข้อมูลก็แสดงว่าการ Query ทำงานได้ 4) มาดูการทำงานของ JavaScript ในส่วนของ jQuery มีการแจ้งเตือนที่ฟังก์ชั่น .on() ซึ่งจะใช้กับ jQuery เวอร์ชั่นใหม่เท่านั้น นั่นหมายถึงเวอร์ชั่น jQuery ที่มากับ Fullcalendar เป็นเวอร์ชั่นเก่า ก็ให้เปลี่ยนไปใช้ .live() แทน ก็จะทำงานได้ปกติ 5) ม...