我有一段与此类似的代码:

<xsl:choose>
   <xsl:when test="some_test">   
      <xsl:value-of select="Something" />
      You are:
      <xsl:variable name="age">12</xsl:variable>
      years
   </xsl:when>
</xsl:choose>

我的问题是我想在选择之外使用变量$ age。我该怎么做?

类似的问题是我的XSLT文件中有几个模板,其中一个是主模板。这一个:

<xsl:template match="/">
</xsl:template>

在这个模板的内部,我调用了其他几个模板,我想再次使用其他模板中的一些变量。

例如,如果我有这段代码:

<xsl:template match="/">
   <xsl:call-template name="search">
   </xsl:call-template>
</xsl:template>

<xsl:template name="search">
   <xsl:variable name="searchVar">Something...</xsl:variable>
</xsl:template>

然后我想在我的主模板中使用$ searchVar。

我认为这是一个同样的问题,但我似乎无法想出这个问题。

顺便说一句,我将Umbraco作为我的CMS运行:)

我希望你们中的一些人有答案。

由于 - 金

有帮助吗?

解决方案

To#1:变量仅在其父元素中有效。这意味着您必须将逻辑放在变量中而不是“在...周围”。它:

<xsl:variable name="var">
  <xsl:choose>
    <xsl:when test="some_test">
      <xsl:text>HEY!</xsl:text>
    </xsl:when>
    <xsl:otherwise>
      <xsl:text>SEE YA!</xsl:text>
    </xsl:otherwise>
  </xsl:choose>
</xsl:variable>

至#2:使用参数将值传输到模板中。

<xsl:template match="/">
  <xsl:variable name="var" select="'something'" />

  <!-- params work for named templates.. -->
  <xsl:call-template name="search">
    <xsl:with-param name="p" select="$var" />
  </xsl:call-template>

  <!-- ...and for normal templates as well -->
  <xsl:apply-templates select="xpath/to/nodes">
    <xsl:with-param name="p" select="$var" />
  </xsl:apply-templates>
</xsl:template>

<!-- named template -->
<xsl:template name="search">
  <xsl:param name="p" />

  <!-- does stuff with $p -->
</xsl:template>

<-- normal template -->
<xsl:template match="nodes">
  <xsl:param name="p" />

  <!-- does stuff with $p -->
</xsl:template>

要将值传回给调用模板,请结合以上内容:

<xsl:template match="/">
  <xsl:variable name="var">
    <xsl:call-template name="age">
      <xsl:with-param name="num" select="28" />
    </xsl:call-template>
  </xsl:variable>

  <xsl:value-of select="$var" />
</xsl:template>

<xsl:template name="age">
  <xsl:param name="num" />

  <xsl:value-of select="concat('You are ', $num, ' years yold!')" />
</xsl:template>

其他提示

查看 xsl:param

修改:未经测试,但可能有效:

<xsl:param name="var">
  <xsl:choose>
   <xsl:when test="some_test">   
     <xsl:value-of select="string('HEY!')" />
   </xsl:when>
  </xsl:choose>
</xsl:param>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top