Optional parameters when calling an XSL template

2020-06-30 06:49发布

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

标签: xslt
4条回答
何必那么认真
2楼-- · 2020-06-30 07:31

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>
查看更多
狗以群分
3楼-- · 2020-06-30 07:38

Please do not use <xsl:param .../> if you do not need it to increase readability.

This works great:

<xsl:template name="inner">
    <xsl:value-of select="$message" />
</xsl:template>

<xsl:template name="outer">
  <xsl:call-template name="inner">
    <xsl:with-param name="message" select="'Welcome'" />
  </xsl:call-template>
</xsl:template>
查看更多
混吃等死
4楼-- · 2020-06-30 07:45

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 full XPath.

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

查看更多
不美不萌又怎样
5楼-- · 2020-06-30 07:48

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.

查看更多
登录 后发表回答