Kotchasan Framework Documentation
Template
Template
Kotchasan\Template เป็นคลาสสำหรับจัดการ Template HTML รองรับการแทนที่ตัวแปร (Variable Replacement) และการโหลดไฟล์ Template จาก Theme
การใช้งานพื้นฐาน
การสร้าง Template จาก HTML
use Kotchasan\Template;
// สร้าง Template จาก String HTML
$html = '<div class="alert">{CONTENT}</div>';
$template = Template::createFromHTML($html);
// แทนที่ตัวแปร {CONTENT} ด้วยข้อความ
// หมายเหตุ: Key ต้องเป็น Regex Pattern
$template->add(['/{CONTENT}/' => 'Hello World']);
// แสดงผล
echo $template->render();
// Output: <div class="alert">Hello World</div>การโหลด Template จากไฟล์
// โหลดไฟล์ my_template.html จาก module 'user'
$template = Template::load('user', '', 'my_template');Methods
createFromHTML(string $html): static
สร้าง Instance ของ Template จาก HTML String
- $html: HTML code ต้นฉบับ
- Returns: Template instance
createFromFile(string $filename): static
สร้าง Instance ของ Template จากไฟล์
- $filename: Path ของไฟล์
add(array $array): static
แทนที่ตัวแปรใน Template ด้วยค่าที่กำหนด
- $array: Array ของ Key (Regex Pattern) และ Value ที่ต้องการแทนที่
[!IMPORTANT]
Key ของ Array ต้องเป็น Regex Pattern เท่านั้น (เช่น/{NAME}/หรือ/^NAME$/) หากใส่เป็น String ธรรมดาจะไม่ทำงาน
$template->add([
'/{TITLE}/' => $title,
'/{CONTENT}/' => $content
]);render(): string
คืนค่า HTML ที่ผ่านการประมวลผลแล้ว
- Returns: HTML String
insertHTML(string $html): static
แทรก HTML ต่อท้ายเนื้อหาปัจจุบันโดยตรง (ไม่ต้องแทนที่ตัวแปร)
init(string $theme)
กำหนด Folder ของ Theme ที่จะใช้งาน (ใช้กับ load())
- $theme: ชื่อ Folder Theme (เช่น 'default')
การใช้งาน Grid
Template รองรับการแสดงผลแบบ Grid (Row/Col) โดยกำหนดค่าผ่าน property (แต่เป็น protected, ปกติใช้ผ่าน subclass Grid)
ตัวอย่างการใช้งานจริง
$view = new Template;
$view->init('default'); // ใช้ Theme 'default'
// โหลด main.html จาก Theme
$template = Template::create('Gcms', 'index', 'main');
// แทนที่เนื้อหา
$template->add([
'/{WEB_TITLE}/' => 'My Website',
'/{CONTENT}/' => 'Welcome to my site'
]);
echo $template->render();