Saturday, June 30, 2007

Lập trình PHP bằng công nghệ template (phần 2)

Trong phần 2 nầy tôi xin trình bày cho các bạn kỹ thuật để xuất một table bằng tempate
Bạn chép file ex2.xtpl và file ex2.php vào thư mục test. Sau đó mở trình duyệt và mở file ex2.php
Trang web sẽ xuất ra như sau:

row nr. id name age
1 38 cocomp 33
2 27 linkhogthrob 34
3 56 pingu 23

Hãy xem nội dung file ex2.xtpl

<!-- BEGIN: main -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Language" content="en" />
<meta name="GENERATOR" content="Co-Comp Ltd" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>example 2</title>
</head>
<!-- $HeadURL: https://xtpl.svn.source...root/xtpl/trunk/ex2.xtpl $
$Id: ex2.xtpl 16 2007-01-11 03:02:49Z cocomp $ -->
<body>
<p>You should see a table with multiple rows:</p>

<!-- BEGIN: table -->
<table border="1">
<tr>
<th>row nr.</th>
<th>id</th>
<th>name</th>
<th>age</th>
</tr>
<!-- BEGIN: row -->
<tr>
<td>{ROW_NR}</td>
<td>{DATA.ID}</td>
<td>{DATA.NAME}</td>
<td>{DATA.AGE}</td>
</tr>
<!-- END: row -->

</table>
<!-- END: table -->

</body>
</html>
<!-- END: main -->
Đầu tiên là block main (begin và end của nó bao trùm hết cả template, bạn hãy nhìn vào đầu và cuối file template nầy). Trong block main có block con, ở đây là block: table, và trong block table là block: row. Trong block row sẽ có các biến dùng để thể hiện các giá trị ra trang web.

Bạn hãy xem nội dung file source: ex2.php
Đây là nội dung file ex2.php
include_once('./xtemplate.class.php');
$xtpl = new XTemplate('ex2.xtpl');
/**
* you can reference to array keys in the template file the following way:
* {DATA.ID} or {DATA.NAME}
* say we have an array from a mysql query with the following fields: ID, NAME, AGE
*/
$rows = array();
// add some data
$rows[1]=array('ID'=>'38',
'NAME'=>'cocomp',
'AGE'=>'33'
);

// add some data
$rows[2]=array('ID'=>'27',
'NAME'=>'linkhogthrob',
'AGE'=>'34'
);
// add some data
$rows[3]=array('ID'=>'56',
'NAME'=>'pingu',
'AGE'=>'23'
);
$rowsize = count($rows);
for ($i = 1; $i <= $rowsize; $i++) {
// assign array data
$xtpl->assign('DATA', $rows[$i]);
$xtpl->assign('ROW_NR', $i);
// parse a row
$xtpl->parse('main.table.row');
// another way to do it would be:
/*
$xtpl->insert_loop('main.table.row', array('DATA'=>$rows[$i],
'ROW_NR'=>$i
));
*/

}
// parse the table
$xtpl->parse('main.table');

$xtpl->parse('main');
$xtpl->out('main');

?>
Ta sẽ có một vòng lặp for để gán các trị cho các row, nhớ rằng mỗi khi assign - gán giá trị xong ta phải parse nó ngay, sau khi parse xong các block row ta sẽ parse block table và cuối cùng parse block main.

No comments: