การทำ Macros และ Functions

ใน Freemarker, macros และ functions ใช้สร้างส่วนที่สามารถใช้ซ้ำได้ใน templates. ซึ่งทั้งสองต่างก็มีหน้าที่ที่คล้ายกัน แต่ macros มักถูกใช้เพื่อแทรกข้อความหรือ HTML ส่วนใหญ่, ในขณะที่ functions มักถูกใช้เพื่อคืนค่า.

1. Macros

เป็นวิธีการสร้างส่วนของ template ที่สามารถใช้ซ้ำได้.

การกำหนด macro:

<#macro sayHello name>
Hello, ${name}!
</#macro>

การเรียกใช้ macro:

<@sayHello name="John" /> 

2. Functions

เป็นวิธีการสร้างฟังก์ชันที่คืนค่าตามที่คุณต้องการ.

การกำหนด function:

<#function add a b> 
<#return a + b>
</#function>

การเรียกใช้ function:

<#assign result = add(5, 3)>
The result is: ${result}
<!-- The result is: 8 -->

การใช้ Macros และ Functions ร่วมกัน:

คุณสามารถนำ macros และ functions มาใช้ร่วมกันใน template เดียวกัน, หรือจะนำเข้าจาก templates อื่นๆ ได้ผ่าน <#import ...>.

ตัวอย่างการนำเข้า macros และ functions:

<#import "myMacrosAndFunctions.ftl" as utils> 
<@utils.sayHello name="Alice" />
The sum is: ${utils.add(4, 5)}

การใช้ macros และ functions ใน Freemarker ทำให้ template ของคุณมีความยืดหยุ่นและความสามารถในการแบ่งปันระหว่าง templates หลายๆ อัน, ช่วยในการเก็บรักษาและอัปเดตได้ง่ายขึ้น.

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