Redirecting internal links to $root URL with xsl:apply-templates
This is an open discussion with 3 replies, filed under XSLT.
Search
It also might help to limit the effects of the templates by specifying a mode. The same concept can also apply to images, by the way:
<xsl:template match="img[substring(@src,1,1)='/']" mode="root-url"> <img> <xsl:apply-templates select="@*"/> <xsl:attribute name="src"><xsl:value-of select="$root"/><xsl:value-of select="@src"/></xsl:attribute> </img> </xsl:template> <xsl:template match="a[substring(@href,1,1)='/']" mode="root-url"> <a> <xsl:apply-templates select="@*"/> <xsl:attribute name="href"><xsl:value-of select="$root"/><xsl:value-of select="@href"/></xsl:attribute> <xsl:value-of select="."/> <xsl:apply-templates select="./*"/> </a> </xsl:template>
Then apply the templates using the following instruction:
<xsl:apply-templates select="body" mode="root-url"/>
I did that? Wow, neat.
I forgot what I did here and spent way too much time trying to figure out what I did, getting stuck on a bug where I was applying templates without a mode. For a complete utility that can be called with
<xsl:apply-templates select="body" mode="root-url"/>
Use a template like this to transform anchors and images to absolute URLs:
<xsl:template match="*" mode="root-url"> <xsl:element name="{name(.)}"> <xsl:apply-templates select="@*" mode="root-url"/> <xsl:apply-templates mode="root-url"/> </xsl:element> </xsl:template> <xsl:template match="@*" mode="root-url"> <xsl:attribute name="{name(.)}"><xsl:value-of select="."/></xsl:attribute> </xsl:template> <xsl:template match="text()" mode="root-url"> <xsl:value-of select="."/> </xsl:template> <xsl:template match="img[substring(@src,1,1)='/']" mode="root-url"> <img> <xsl:apply-templates select="@*" mode="root-url"/> <xsl:attribute name="src"><xsl:value-of select="$root"/><xsl:value-of select="@src"/></xsl:attribute> </img> </xsl:template> <xsl:template match="a[substring(@href,1,1)='/']" mode="root-url"> <a> <xsl:apply-templates select="@*" mode="root-url"/> <xsl:attribute name="href"><xsl:value-of select="$root"/><xsl:value-of select="@href"/></xsl:attribute> <xsl:value-of select="."/> <xsl:apply-templates select="./*" mode="root-url"/> </a> </xsl:template>
Create an account or sign in to comment.
Allen put this file together a while ago and I added an additional template for managing internal links within entries.
Create internal links with an absolute URL starting with a slash, then use this template to change the URL in your entries to your
$root
URL of your site, regardless of whether your site is at the root of a domain or deep in a subdirectory.Add the attached utility to your page template:
Apply the
typography.xsl
templates to your data by using an instruction similar to the following:Works like magic.
Attachments