แท็ก <x:if> ประเมินค่า test XPath Expression ถ้าเป็น true จะรัน body ถ้า false จะข้ามไป
แอตทริบิวต์ของ <x:if>
| แอตทริบิวต์ | คำอธิบาย | จำเป็น | ค่าเริ่มต้น |
|---|---|---|---|
| select | XPath Expression ที่ต้องการประเมิน | ใช่ | None |
| var | ชื่อตัวแปรเก็บผลลัพธ์ true/false | ไม่ | None |
| scope | ขอบเขตของตัวแปร | ไม่ | Page |
ตัวอย่างการใช้งาน
<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="https://java.sun.com/jsp/jstl/xml" %>
<html>
<head>
<title>JSTL x:if Tags</title>
</head>
<body>
<h3>Books Info:</h3>
<c:set var="xmltext">
<books>
<book>
<name>Padam History</name>
<author>ZARA</author>
<price>100</price>
</book>
<book>
<name>Great Mistry</name>
<author>NUHA</author>
<price>2000</price>
</book>
</books>
</c:set>
<x:parse xml="${xmltext}" var="output"/>
<x:if select="$output//book">
เอกสารมี element <book> อย่างน้อย 1 รายการ
</x:if>
<br />
<x:if select="$output/books[1]/book/price > 100">
ราคาหนังสือสูงมาก
</x:if>
</body>
</html>
ผลลัพธ์
Books Info: เอกสารมี element <book> อย่างน้อย 1 รายการ ราคาหนังสือสูงมาก
เงื่อนไขแรก true เพราะมี book 2 เล่ม เงื่อนไขที่สอง true เพราะราคาเล่มที่ 2 คือ 2000 > 100