2

I use XSLT to generate an HTML table using info from an XML file. I want only 4 TD in every TR.

It works fine on Chrome and Safari. Not in Firefox. I understand that Firefox doesn't support 'disable-output-escaping' so I know that is the problem (it just writes on the web page) . Is there another way to generate this kind of (simple) table with XSLT on client side?

My code looks like this:

<table>
<xsl:for-each select="movies/movie">
   <xsl:if test="(position() = 1) or ((position() mod 4) = 1)">
       <!-- This is a <tr> -->
      <xsl:text disable-output-escaping="yes">&lt;tr&gt;</xsl:text>
   </xsl:if>
   <td>
     <!-- Some stuff goes here. -->
   </td>
   <xsl:if test="((position() mod 4) = 0) or (position() = last())">
       <!-- This is a </tr> -->
      <xsl:text disable-output-escaping="yes">&lt;/tr&gt;</xsl:text>
   </xsl:if> 
</xsl:for-each>
</table>
1
  • 1
    Can you post a sample of the XML that you're transforming? Commented Oct 26, 2011 at 19:33

2 Answers 2

2
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/">
    <table>
      <xsl:apply-templates select="movies/movie[position() mod 4 = 1]"/>
    </table>
  </xsl:template>

  <xsl:template match="movie">
    <tr>
      <xsl:for-each select=". | following-sibling::movie[position() &lt; 4]">
        <td>
          <xsl:value-of select="."/>
        </td>
      </xsl:for-each>
    </tr>
  </xsl:template>

</xsl:stylesheet>

Input XML:

<movies>
  <movie>a</movie>
  <movie>b</movie>
  <movie>c</movie>
  <movie>d</movie>
  <movie>e</movie>
  <movie>f</movie>
  <movie>g</movie>
  <movie>h</movie>
</movies>

Output XML:

<table>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
    <td>d</td>
  </tr>
  <tr>
    <td>e</td>
    <td>f</td>
    <td>g</td>
    <td>h</td>
  </tr>
</table>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This must be the XSLT way :)
1

Have you tried something like this?

<table>
<tr><xsl:apply-templates select='movies/movie' /></tr>
</table>

And then, in another template

<xsl:template match='movie'>
   <td><xsl:value-of select='.' /></td>
</xsl>

Remember that you should try and think about XSLT as a template system, more than as a programming language. Using XSLT-specific constructs is usually more straightforward than trying to translate other constructs.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.