Domanda

I'm looking for a way of removing all line breaks in a particular XSL template within my stylesheet, not the whole stylesheet, just the template.

I have a template which renders a JSON block of code.

For example, in my XSLT stylesheet I have the following:

<xsl:template match="/">
   <div>Content here..</div>

   <xsl:call-template name="Foo">
      <xsl:with-param name="Bar" select="Bar" />
   </xsl:call-template>

   <div>Content here..</div>
</xsl:template>

<xsl:template name="Foo">
   <xsl:param name="Bar" />
   <script type="text/javascript">
      var json = {
          data:[
             <xsl:for-each select="$Bar">
                 {
                    ID:<xsl:value-of select="@Baz"/>
                 }
                 <xsl:if test="position() != last()">,</xsl:if>
             </xsl:for-each>
          ]
      };
   </script>
</xsl:template>

This will render as something like:

<div>Content here..</div>

<script type="text/javascript">
   var json = {
      data:[

         {
            ID:1
         }
         ,
         {
            ID:2
         }
         ,
         {
            ID:3
         }

       ]
    };
</script>

<div>Content here..</div>

I would prefer this to render as:

<div>Content here..</div>

<script type="text/javascript">var json = {data:[{ID:1},{ID:2},{ID:3}]};</script>

<div>Content here..</div>

Is this possible, without having to make my XSL template become unreadable?

È stato utile?

Soluzione

Wrapping the JAvaScript code in xsl:text elements will help you to achieve the desired result.

<script type="text/javascript">
    <xsl:text>var json = {data:[</xsl:text>
    <xsl:for-each select="$Bar">
        <xsl:text>{ID:</xsl:text>
        <xsl:value-of select="@Baz"/>
        <xsl:text>}</xsl:text>
        <xsl:if test="position() != last()">,</xsl:if>
    </xsl:for-each>
    <xsl:text>]};</xsl:text>
</script>

It isn't the nicest piece of code, but I think it's still readable. Let me know if it works.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top