XSLT <xsl:variable>
❮ ทำการอ้างอิงองค์ประกอบ XSLT ให้สมบูรณ์
ความหมายและการใช้งาน
<xsl:variable> องค์ประกอบใช้เพื่อประกาศตัวแปรท้องถิ่นหรือตัวแปรส่วนกลาง
หมายเหตุ:ตัวแปรจะเป็นค่าสากลหากประกาศเป็นองค์ประกอบระดับบนสุด และเป็นตัวแปรภายในหากประกาศภายในเทมเพลต
หมายเหตุ:เมื่อคุณตั้งค่าตัวแปรแล้ว คุณจะไม่สามารถเปลี่ยนหรือแก้ไขค่านั้นได้!
เคล็ดลับ:คุณสามารถเพิ่มค่าให้กับตัวแปรโดยเนื้อหาขององค์ประกอบ <xsl:variable> หรือโดยแอตทริบิวต์ select!
ไวยากรณ์
<xsl:variable
name="name"
select="expression">
<!-- Content:template -->
</xsl:variable>
คุณลักษณะ
Attribute | Value | Description |
---|---|---|
name | name | Required. Specifies the name of the variable |
select | expression | Optional. Defines the value of the variable |
ตัวอย่าง 1
หากมีแอตทริบิวต์ select อยู่ องค์ประกอบ <xsl:variable> จะไม่มีเนื้อหาใดๆ หากแอตทริบิวต์ select มีสตริงตามตัวอักษร สตริงนั้นต้องอยู่ภายในเครื่องหมายคำพูด สองตัวอย่างต่อไปนี้กำหนดค่า "สีแดง" ให้กับตัวแปร "สี":
<xsl:variable name="color" select="'red'" />
<xsl:variable name="color" select='"red"' />
ตัวอย่าง 2
หากองค์ประกอบ <xsl:variable> มีแอตทริบิวต์ name เท่านั้น และไม่มีเนื้อหา ค่าของตัวแปรจะเป็นสตริงว่าง:
<xsl:variable name="j" />
ตัวอย่างที่ 3
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:variable
name="header">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
</xsl:variable>
<xsl:template
match="/">
<html>
<body>
<table border="1">
<xsl:copy-of select="$header" />
<xsl:for-each
select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
❮ ทำการอ้างอิงองค์ประกอบ XSLT ให้สมบูรณ์