Re: [xsl] How to detect if the context item exists

Subject: Re: [xsl] How to detect if the context item exists
From: David Carlisle <davidc@xxxxxxxxx>
Date: Fri, 01 Jul 2011 00:03:52 +0100
On 30/06/2011 21:23, Michael Kay wrote:
No, within a named template it's not statically decidable. The named
template might be called from within a function.

yes (that's the usual way the context gets undefined) but what I meant was that the author of the stylesheet can write the template as


<xsl:template name=x">
<xsl:param name="hascontext" select="true()"/>
..

then use

<xsl:call-template name="x">
  <xsl:with-param name="hascontext" select="false()"/>

whenever it is being called from within a function. In theory chained named template application make it hard to know when you have no current item, but in practice for most stylesheets you probably know.
that way, the template has available a boolean that's true if there is a current item.



Trouble is even if you have the boolean with the right value at runtime its not easy to guard the relevant xpaths that would generate an error.

when i was playing wuth xquery to xslt conversion a while back and came up against this quite a lot, I found it easiest just to ensure that there was always a current item (or that the code was skipped) by never using the implicit current item for a named template and always doing

<xsl:template name=x">
<xsl:param name="context" select="()"/>
  <xsl:value-of select="$context/a/b/c"/>

then passing in "." as the context param just at points that you know it's available, which ends up being more or less equivalent to just always using functions and always passing the context explicitly (which, unsurprisingly given the context of that project, is essentially the xquery way of doing things)

David

Current Thread