Monday 11 February 2008

Setting Query String Parameters in Xslt

In Xslt, adding a new parameter to a query string presents a problem as, without writing your own extension function, you cannot determine whether you should prefix your parameter with ‘?’ or ‘&’. In Sitecore, the Xslt function sc:qs('parametername') can be used to obtain the value of a named parameter parametername. Unfortunately, there is no function provided that obtains the entire query string.

Here’s a workaround. Let’s say you want to add a parameter called ‘page’.

First, build up the rest of the query string. The following template checks the existence in the query string of parameter names passed to it. You need to know the names of the possible parameters. If they exist, they are written out.

<xsl:template name="SetQueryParameter">
<xsl:param name="name" />
<xsl:if test="sc:qs($name)">
<xsl:text>&amp;</xsl:text>
<xsl:value-of select="$name" />
<xsl:text>=</xsl:text>
<xsl:value-of select="sc:qs($name)" />
</xsl:if>
</xsl:template>

This template would typically be called from within a variable definition, therefore saving the created query string. In the following example, we are checking parameters type and orderby and saving them if they exist so we can add them back in later:

<xsl:variable name="RestOfQueryString">
<xsl:call-template name="SetQueryParameter">
<xsl:with-param name="name">type</xsl:with-param>
</xsl:call-template>
<xsl:call-template name="SetQueryParameter">
<xsl:with-param name="name">orderby</xsl:with-param>
</xsl:call-template>
</xsl:variable>

You are then able to append this query string to your newly-added parameter, which you add using a ‘?’:

<a>
<xsl:attribute name="href">
<xsl:text>?page=10</xsl:text>
<xsl:value-of select="$RestOfQueryString" />
</xsl:attribute>
<xsl:text>Page 10</xsl:text>
</a>

No comments: