การใช้งาน loops และ conditions

การใช้งาน loops และ conditions เป็นส่วนสำคัญของการสร้างเทมเพลตใน Freemarker. ด้านล่างนี้คือรายละเอียดเกี่ยวกับการใช้งาน:

1. Loops:

1.1 การวนซ้ำในรายการ (List):

<#list items as item>
${item_index}. ${item}
</#list>

item_index คือตัวแปรที่แทนดัชนีของแต่ละรายการ (เริ่มต้นจาก 0)

items คือรายการที่คุณต้องการวนซ้ำ

item คือตัวแปรที่แทนค่าของแต่ละรายการ

1.2 การวนซ้ำในแมพ (Map):

<#list map as key, value>
${key}: ${value}
</#list>

2. Conditions:

2.1 การใช้งาน if:

<#if condition> 
This will be displayed if the condition is true.
</#if>

2.2 การใช้งาน if-else:

<#if username == "John">
Hello, John!
<#else>
Hello, guest!
</#if>

2.3 การใช้งาน if-elseif-else:

<#if score > 90>
Excellent!
<#elseif score > 70>
Good job!
<#else>
Keep trying!
</#if>

2.4 การใช้ switch-case:

Freemarker ไม่มีโครงสร้าง switch-case โดยตรง, แต่คุณสามารถสร้างโครงสร้างที่คล้ายคลึงกันได้โดยใช้ if-elseif-else.

<#if color == "red">
It's a red color.
<#elseif color == "blue">
It's a blue color.
<#else>
Unknown color.
</#if>

ด้วยข้อมูลเหล่านี้, คุณสามารถใช้ loops และ conditions ใน Freemarker เพื่อประมวลผลและแสดงผลข้อมูลในรูปแบบต่าง ๆ ได้.

จำนวนคนดู : 1,284 วันที่สร้าง : 08/09/2023