tags:

views:

756

answers:

3

Is there way to call an XSL template with optional parameters?

For example:

<xsl:call-template name="test">
  <xsl:with-param name="foo" select="'fooValue'" />
  <xsl:with-param name="bar" select="'barValue'" />
</xsl:call-template>

And the resulting template definition:

<xsl:template name="foo">
  <xsl:param name="foo" select="$foo" />
  <xsl:param name="bar" select="$bar" />
  <xsl:param name="baz" select="$baz" />
  ...possibly more params...
</xsl:template>

This code will gives me an error "Expression error: variable 'baz' not found." Is it possible to leave out the "baz" declaration?

Thank you, Henry

+6  A: 

You're using the xsl:param syntax wrong.

Do this instead:

<xsl:template name="foo">
  <xsl:param name="foo" />
  <xsl:param name="bar" />
  <xsl:param name="baz" select="DEFAULT VALUE" />
  ...possibly more params...
</xsl:template>

Param takes the value of the parameter passed using the xsl:with-param that matches the name of the xsl:param statement. If none is provided it takes the value of the select attribute.

More details can be found on W3School's entry on param.

Welbog
That did the trick......thank you!!!!
HumanSky
+2  A: 

The value in the select part of the param element will be used if you don't pass a parameter.

You are getting an error because the variable or parameter $baz does not exist yet. It would have to be defined at the top level for it to work in your example, which is not what you wanted anyway.

Also if you are passing a literal value to a template then you should pass it like this.

<xsl:call-template name="test">  
    <xsl:with-param name="foo">fooValue</xsl:with-param>
BeWarned
A: 

Personally, I prefer doing the following:

<xsl:call-template name="test">  
   <xsl:with-param name="foo">
      <xsl:text>fooValue</xsl:text>
   </xsl:with-param>

I like using explicitly with text so that I can use XPath on my XSL to do searches. It has come in handy many times when doing analysis on an XSL I didn't write or didn't remember.