XSL for-each 2个元素在容器中变形

时间:2014-02-13 06:20:42

标签: xslt

我有一个xsl文件,我从模板中获取内容,如果有2个元素,则需要在容器中扭曲每个2个元素。

我的代码是这样的:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output indent="yes" method="html"/>

<xsl:template name="type0">
    <div class="content"></div>    
</xsl:template>

<xsl:template name="teaser>
    <xsl:param name="pos" select="1" />
    <xsl:call-template name="type0">
        <xsl:with-param name="pos" select="$pos" />
    </xsl:call-template>
</xsl:template>

<xsl:template match="frontpage">
    <div class="container">
        <xsl:call-template name="teaser />
    </div>
</xsl:template>

输出必须像这样(如果我创建了5个元素):

<div class="container">
    <div class="content"></div>
    <div class="content"></div>
</div>
<div class="container">
    <div class="content"></div>
    <div class="content"></div>
</div>
<div class="container">
    <div class="content"></div>
</div>

知道这有可能吗?

修改

我已经尝试实现了Thomas W.的建议,但它失败了,它无法编译样式表。我在这段代码中做了些什么工作:

<xsl:template match="type0" mode="generate-container-content">
    <div class="content"></div>    
</xsl:template>

<xsl:template name="teaser">
    <xsl:param name="pos" select="1" />

    <div class="container">
        <xsl:template match="type0[position() mod 2 = 1]">
            <xsl:apply-templates select=".|following-sibling::type0[1]" mode="generate-container-content">
                <xsl:with-param name="pos" select="$pos" />
            </xsl:apply-templates>
        </xsl:template>
    </div>
</xsl:template>
<xsl:template match="frontpage">
    <xsl:call-template name="teaser" />
</xsl:template>

1 个答案:

答案 0 :(得分:1)

假设您有一个<someElement>元素列表,那么您可以使用模式并执行以下操作(请参阅注释以获得解释):

<!-- Only generate a container for elements at uneven position
  (1st, 3dr, 5th etc.) -->
<xsl:template match="someElement[position() mod 2 = 1]">
  <div class="container">
    <!-- Use a different mode for actually creating the content elements 
      We need to use the mode for distinguishing between templates that 
      match elements in the list for creating the container and ones that
      match for creating content. -->
    <xsl:apply-templates select=".|following-sibling::someElement[1]"
      mode="generate-container-content"/>
  </div>
</xsl:template>

<!-- Don't generate anything for any other elements that are not 
  matched by the template above (the even-positioned ones remain) -->
<xsl:template match="someElement"/>

<xsl:template match="someElement" mode="generate-container-content">
  <div class="content">
    Generate whatever the content looks like
  </div>
</xsl:template>