Sitecore’s XSLT renderings are an excellent way to quickly and easily render almost any part of your web app or site. In interacting with the developer community through blogs, StackOverflow, etc. I believe they are largely misunderstood. I have not found a way to go from HTML mockup to functioning website faster than using XSLT simply filling in the blanks. So, to those of you brave enough to try it out, check this out.
That being said, there are a few gotchas to consider when putting your renderings together.
Item or Node Comparison
1 2 3 4 5 6
<xsl:for-each select="./item"> <xsl:if test="$some_item = ."> <!-- Incredible code happening here --> </xsl:if> </xsl:for-each>
Now consider the difference on line 2 in the following modified version of the code snippet.
1 2 3 4 5 6
<xsl:for-each select="./item"> <xsl:if test="$some_item/@id = ./@id"> <!-- Incredible code happening here --> </xsl:if> </xsl:for-each>
In the first example it was necessary to serialize the whole item and compare that, whereas the second example simply compares to id attribute. Depending on your needs comparing item ids is enough – keep in mind how expensive the comparisons are.
Sometimes a descendant query is necessary but until now they haven’t been scalable. Where I often see them is in navigation components to determine if a navigation element should have a “selected” state. If you imagine the content tree with it’s children and their children… this query will potentially touch a lot of nodes!
Check out some code you might see in a navigation control below
1 2 3
<xsl:foreach select="$home/item"> <xsl:when test="boolean(current()/descendant-or-self::item[@id=$sc_currentitem/@id])"> ...
That might not make your head shake at first glance, but it should. Now compare line 2 to the same line in the following snippet
1 2 3
<xsl:foreach select="$home/item"> <xsl:when test="boolean($sc_currentitem/ancestor-or-self::item[@id = current()/@id])"> ...
That particular blunder can be done in a user control too. Be cognizant of the number of items your query is going to touch. It might be fast in your development environment where there are only 3 news articles, but 6 months later in production they might have hundreds or thousands – that’s not scalable my friend.
“Yeah, that’s why I don’t use XSLT”
I’m going to nip that conversation in the bud. No matter what technology you’re using, Schlemiel the Painter has an algorithm. Understanding the fundamentals about the system you’re developing for are key. Any other ProTip™ share in the comments below – I continue to learn everyday. :)