1

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

<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 运行 :)

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

谢谢 - 金

4

2 回答 2

2

到 #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>

To #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>
于 2009-09-11T11:40:44.997 回答
0

看看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>
于 2009-09-11T10:10:27.210 回答