在XSL中使用if条件设置变量值

8

我有一个基础条件,检查变量是否为空,如果是,则将变量设置为特定值,如下所示。

<xsl:variable name="PIC" select="avatar"/>

<xsl:choose>
  <xsl:when test="avatar !=''">
    <xsl:variable name="PIC" select="avatar"/>
  </xsl:when>
  <xsl:otherwise>
    <xsl:variable name="PIC" select="'placeholder.jpg'"/>
  </xsl:otherwise>
</xsl:choose>

基本上,变量PIC设置为avatar返回的任何内容。然后进行测试以检查它是否为空并分配给变量PIC,如果为空,则将值placeholder.jpg添加到变量PIC中。

现在由于某种原因,我一直收到以下警告

没有跟随兄弟指令的变量没有效果

您有什么想法这里做错了吗?

2个回答

15

XSLT中的变量是不可变的,一旦设置就无法更改。在xsl:choose中的变量声明只是新的声明,仅在当前块的本地范围内有效。它们被称为“遮蔽”初始变量。

你需要做的是...

<xsl:variable name="PIC">
   <xsl:choose>
     <xsl:when test="avatar !=''">
        <xsl:value-of select="avatar"/>
     </xsl:when>
     <xsl:otherwise>
       <xsl:value-of select="'placeholder.jpg'"/>
     </xsl:otherwise>
   </xsl:choose>
</xsl:variable>

今天学到了新东西,感谢你对示例背后的详细解释,非常感谢 Tim。 - BaconJuice

0

使用单个xsl:variable作为<xsl:variable name="PIC" select="if (avatar != '') then avatar else 'placeholder.jpg'"/>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接