1

I have a big set of XSLT templates that generate <div> elements with assorted content. Matches look like these:

<xsl:template match="block[@name = 'block_blah']">
    <div>
       blah
       <div>foooo</div>
    </div>
</xsl:template>

<xsl:template match="block[@name = 'block2']">
    <div>
       <div>xyz</div>
       abc
    </div>
</xsl:template>

I need to add an attribute to every first level <div>. So the output will become:

    <div data-blockname="block_blah">
       blah
       <div>foooo</div>
    </div>

    <div data-blockname="block2">
       <div>xyz</div>
       abc
    </div>

Do I have to insert data-blockname="{@name}" manually in every case? Or is there a way to inject it globally?

4

1 回答 1

1

There is no way to do this "globally" as you say, but there are ways to restructure your XSLT and avoid repetition, like this:

<xsl:template match="block[@name]">
    <div name="{@name}">
      <xsl:apply-templates select="." mode="content" />
    </div>
<xsl:template>

<xsl:template match="block[@name = 'block_blah']" mode="content">
       blah
       <div>foooo</div>
</xsl:template>

<xsl:template match="block[@name = 'block2']" mode="content">
       <div>xyz</div>
       abc
</xsl:template>
于 2013-03-01T12:46:59.187 回答