Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSLT: How to reuse a template within another template

Tags:

xml

xslt

If I have a template as follows, which is used to create a button:

<xsl:template match="button" name="button">
  <a class="button" href="{@href}">
    <xsl:value-of select="@name"/>
  </a>
</xsl:template>

I want to be able to use that button in another template, like this:

<xsl:template match="createForm">
  ...
  <button name="Create" href="/create"/>
</xsl:template>

However, this will just output the button tag as-is. I would like it to be processed through the existing button template. How can this be achieved?

--

Thanks David M for your answer. Here is what I have now for the button template:

<xsl:template match="button" name="button">
  <xsl:param name="name" select="@name"/>
  <xsl:param name="href" select="@href"/>
  <a class="button" href="{$href}">
    <xsl:value-of select="$name"/>
  </a>
</xsl:template>

The createForm template now looks like this:

<xsl:template match="createForm">
  ...
  <xsl:call-template name="button">
    <xsl:with-param name="name" select="'Create'"/>
  </xsl:call-template>
</xsl:template>
like image 536
Joel Avatar asked Jul 04 '09 10:07

Joel


2 Answers

Try using this (off the top of my head):

<xsl:call-template name="button">
    <xsl:with-param name="name" value="Create" />
    <xsl:with-param name="href" value="/create" />
</xsl:call-template>

You'll also need to declare your two parameters within your button template using <xsl:param ...>.

like image 70
David M Avatar answered Sep 19 '22 07:09

David M


As long as you use <xsl:include ... /> or <xsl:import ... />, you should be able to use either of:

<xsl:apply-templates select="button"/> <!-- or your own selector -->

(which assumes there are button elements under the context node)

or <xsl:call-template/> using the name

like image 26
Marc Gravell Avatar answered Sep 22 '22 07:09

Marc Gravell