問題描述
xslt 將變量發送到另一個模板 (xslt send variable to another template)
I have an xml example like this:
<p class="exer_header" style="display: none;">
<image‑input size="5" value="val1" />
</p>
<p class="exer_header" style="display: none;">
<image‑input size="5" value="val2" />
</p>
<answers‑img>
<answer‑img class="imagednd_answer1" value="val1"/>
<answer‑img class="imagednd_answer2" value="val2"/>
</answers‑img>
and XSLT ex. here:
<xsl:template match="image‑input">
<xsl:variable name="id" select="generate‑id(.)"/>
<xsl:element name="input">
<xsl:attribute name="id"><xsl:value‑of select="$id"/></xsl:attribute>
<xsl:attribute name="class">exer_input</xsl:attribute>
</xsl:element>
</xsl:template>
<xsl:template match="answers‑img">
<xsl:for‑each select="//image‑input">
<xsl:element name="div">
<xsl:element name="input">
<xsl:attribute name="class">ans_img_input</xsl:attribute>
<xsl:attribute name="type">hidden</xsl:attribute>
<xsl:attribute name="value">***{ID}***</xsl:attribute>
</xsl:element>
<xsl:apply‑templates select="//answers‑img/answer‑img"/>
</xsl:element>
</xsl:for‑each>
</xsl:template>
Question is next, How can I send a variable id from "input" template into another "answers‑img" template and change {ID}?
UPD: In "answer‑img" I need the same id's that generates in "input‑img". First xslt generate code with "input‑img"(twice) and when somewhere another templates, not in "input‑img", call template "answer‑img". Maybe I can create global array variable?
參考解法
方法 1:
Use xsl:with‑param
I don't know where you want to call the template but it can be done like this:
<xsl:call‑template name="answers‑img"><xsl:with‑param name="id" select="$id" /></xsl:call‑template>
You must add this to the calling template:
<xsl:param name="id" />
方法 2:
For more details how to work with call‑template and param you may visit ‑http://www.w3schools.com/xsl/el_with‑param.asp
方法 3:
Looks like your answers‑img template is looping over image‑input and you like to have the same id as is used in image‑input template. In this case you can create the id the same way as you did in image‑input template.
<xsl:for‑each select="//image‑input">
<xsl:variable name="id" select="generate‑id(.)"/>
.....
<xsl:attribute name="value"><xsl:value‑of select="$id"/></xsl:attribute>
This will work because generate‑id() will allways create the same value for the same element.
Update addressing the concrete question:
How can I send a variable id from "input" template into another "answers‑img" template and change {ID}?
Answer: You can't At least not in your example code. It is only possible to pass a value from an caller (template) to an called (template.)
(by imCaps、Peter Bartels、Navin Rawat、hr_117)