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

สอนเขียน 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 นะครับ และด้านล่างนี้ก็เป็นระบบต่างๆที่แจกให้นำไปลองใช้ลองศึกษากันครับ

สร้างแบบฟอร์มล็อกอิน HTML + PHP

       ผมจะสร้างระบบตัวอย่างเพื่อแสดงให้เห็นการทำงานของสคริปต์ PHP ที่ใช้ในการล็อกอินอย่างง่ายๆ นะครับ โดยที่ผมจะสร้างโฟลเดอร์ใหม่ขึ้นในไดร์ฟที่เราได้กำหนดให้เป็น Directory Root สำหรับรันสคริปต์ PHP ซึ่งผมกำหนดเอาไว้ที่ D:\www ดังนั้นผมจะสร้างโฟลเดอร์ teacher_assistant ขึ้นมาใหม่จะได้พาธเป็น D:\www\teacher_assistant สำหรับการเข้าถึง จะใช้ URL ดังนี้ http://localhost/teacher_assistant หลังจากสร้างโฟลเดอร์เสร็จเรียบร้อยก็จะเริ่มกระบวนการเตรียมโครงสร้างโปรเจ็กต์ด้วยเครื่องมือช่วยเขียนโปรแกรมชื่อว่า eclipse ซึ่งดูวิธีการสร้างโปรเจ็กต์ได้จากบทความ เริ่มต้นสร้างโปรเจ็กต์ ด้วยโปรแกรม eclipse เครื่องมือเขียนโปรแกรม php ในบทความเป็นการสร้างโปรเจ็กต์ที่มีพาธเป็นโฟลเดอร์ login แต่ในที่นี้ต้องเป็นพาธให้ตรงกับโฟลเดอร์ใหม่ที่เราได้สร้างขึ้นด้วยนะครับ

PHP กับการคิดส่วนลดเป็นเปอร์เซ็น 5%, 10%, 20% ตามช่วงราคาที่กำหนด

<?php     $total_price = 1000;     $discount = 0;         if($total_price >= 500 && $total_price < 1001){         $discount = 5;     }elseif($total_price >= 1001 && $total_price <= 5000){         $discount = 10;     }elseif($total_price >= 5001){         $discount = 20;     }         $discount_bath = ($total_price*$discount)/100; ?> <pre> ซื้อสินค้าครบ 0 ถึง 499 บาท ไม่ได้ส่วนลด ซื้อสินค้าครบ 500 ถึง 1000 บาท ได้ส่วนลด 5% ซื้อสินค้าครบ 1001 ถึง 5000บาท ได้ส่วนลด 10% ซื้อสินค้าครบ 5001 บาทขึ้นไป ได้ส่วนลด 20% </pre> <h3>รวมราคาสินค้า = <?php echo number_format($total_price,2);?></h3> <h5>ส่วนลด = <?php echo $discount;?>%  (<?php echo $discount_bath;?> บาท)</h5> <h2>ราคาหลังส่วนลด = <?php echo number_format($total_price - $discount_bath,2);?>บาท</h2> "PHP ไม่ได้สร้างสุดยอดโปรแกรม แต่ PHP ช่วยให้งานคุณง่ายขึ้นต