Optional parameters when calling an XSL template

前端 未结 4 1468
广开言路
广开言路 2021-02-18 14:36

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

For example:


  

        
相关标签:
4条回答
  • 2021-02-18 15:03

    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.

    0 讨论(0)
  • 2021-02-18 15:04

    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.

    0 讨论(0)
  • 2021-02-18 15:14

    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>
    
    0 讨论(0)
  • 2021-02-18 15:22

    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>
    
    0 讨论(0)
提交回复
热议问题