Re: [xsl] Indent based on position()

Subject: Re: [xsl] Indent based on position()
From: Jeni Tennison <jeni@xxxxxxxxxxxxxxxx>
Date: Thu, 11 Apr 2002 13:05:33 +0100
Hi Brook,

> So, when i process each <line> I need to duplicate the "-" character
> as many times as the position() of the <line> being processed, I
> think. Can I do this?

Yes. I think the easiest way would be to use the Piez method of
iterating over the correct number of nodes to repeat the same string:

  <xsl:for-each select="...the right number of nodes...">-</xsl:for-each>

In your case, getting hold of the correct number of nodes is easy --
you can collect together all the preceding sibling of the line, plus
the line itself:

<xsl:template match="line">
  <xsl:for-each select=". | preceding-sibling::line">-</xsl:for-each>
  <xsl:apply-templates />
  <br />
</xsl:template>

If you have lots and lots of lines in each content, you might find a
step-by-step method more efficient. For that, apply templates to only
the first line:

<xsl:template match="content">
  <p>
    <xsl:apply-templates select="line[1]" />
  </p>
</xsl:template>

Then have a template for the line element that gets passed in the
right number of '-'s as a parameter, prints that out, then the line,
then the br element, and then applies templates to the immediately
following sibling line, adding one hyphen to the indent:

<xsl:template match="line">
  <xsl:param name="indent" select="'-'" />
  <xsl:value-of select="$indent" />
  <xsl:apply-templates />
  <br />
  <xsl:apply-templates select="following-sibling::line[1]">
    <xsl:with-param name="indent" select="concat($indent, '-')" />
  </xsl:apply-templates>
</xsl:template>

---

In XSLT 2.0, you could do:

<xsl:template match="line">
  <xsl:for-each select="1 to position()">-</xsl:for-each>
  <xsl:apply-templates />
  <br />
</xsl:template>

or:

<xsl:template match="line">
  <xsl:value-of select="for $i in 1 to position() return '-'"
                separator="" />
  <xsl:apply-templates />
  <br />
</xsl:template>

Cheers,

Jeni

---
Jeni Tennison
http://www.jenitennison.com/


 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list


Current Thread