การทำ Nested Templates ใน Freemarker หมายถึงการแทรก template หนึ่งภายใน template อื่นๆ ซึ่งทำให้คุณสามารถมีโครงสร้างที่เรียบง่ายและสามารถรักษาได้ง่ายเมื่อมีการเปลี่ยนแปลง. นี่เป็นวิธีที่ดีในการจัดการกับส่วนต่างๆ ของเว็บไซต์ หรือเอกสารที่มีโครงสร้างที่คล้ายกัน.
ต่อไปนี้คือวิธีการทำ Nested Templates ใน Freemarker:
สร้าง Main Template:
สมมติว่าคุณมี main.ftl ซึ่งจะเป็น template หลัก:
<html>
 <head>
 <title>
${title}
</title>
 </head>
 <body>
 <#include "header.ftl">
 ${content} 
<#include "footer.ftl">
 </body>
 </html> 
สร้าง Sub-Templates:
header.ftl:
<header>
 Welcome to our website! 
</header> 
footer.ftl:
<footer>
 Copyright © 2023. All rights reserved. 
</footer> 
เตรียม Data Model:
สมมติว่าคุณมี Java code ที่กำหนดข้อมูลเหล่านี้:
Map<String, Object>
 dataModel = new HashMap<>(); 
dataModel.put("title", "My Website"); 
dataModel.put("content", "
<p>
This is the main content of the page.
</p>"); 
ประมวลผล Template:
ใช้ Java code ที่คุณมีเพื่อประมวลผล main.ftl ด้วย dataModel:
Template mainTemplate = cfg.getTemplate("main.ftl"); 
Writer out = new OutputStreamWriter(System.out); 
mainTemplate.process(dataModel, out); 
ผลลัพธ์จะเป็น HTML ที่มี header, content, และ footer แทรกอยู่ภายใน main.ftl.
การใช้ Nested Templates ทำให้คุณสามารถจัดระเบียบและจัดการกับ code ของคุณได้ง่ายขึ้น, เนื่องจากคุณสามารถแยกส่วนต่างๆ ของเว็บเพจหรือเอกสารออกเป็น templates ย่อยๆ และนำมาใช้ซ้ำได้ตามความต้องการ.
| จำนวนคนดู : 2,287 | วันที่สร้าง : 08/09/2023 |