Insert attributes on-the-fly to an “a” tag
Pregunta
I need to modify on-the-fly the "content" of all the "a" tags present in a specific div (#navigation).
Is there a diazo rule or xslt pattern?
Thank's Vito
Solución
The following demonstrates adding an attribute (in this case target
) to each of the a
tags that are child elements under an element with the id of navigation
(so corresponding to #navigation
in CSS). All content and other attributes from the original tags are maintained (although order may not be - though this shouldn't be an issue).
<?xml version="1.0" encoding="UTF-8"?>
<rules xmlns="http://namespaces.plone.org/diazo"
xmlns:css="http://namespaces.plone.org/diazo/css"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<after css:theme="#target" css:content="#navigation" />
<xsl:template match="*[@id='navigation']//a">
<xsl:copy>
<xsl:attribute name="target">_blank</xsl:attribute>
<xsl:copy-of select="@*" />
<xsl:apply-templates />
</xsl:copy>
</xsl:template>
</rules>
Adjust the match
condition accordingly with additional conditions if you want to match specific a
tags. The xsl:template
will be executed after all standard Diazo rules, so ensure that you adjust the match
condition accordingly if you happen to change the structure of where the a
tags are in your resulting document.
This was extended an example in the official Diazo documentation at http://docs.diazo.org/en/latest/recipes/adding-an-attribute/index.html
Otros consejos
Not sure what you mean. If you want to create an XSLT that copies everything but tweak only the "a" elements inside the div id='navigation' you should do something like this:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" />
<xsl:template match="@*|node()" priority="-1">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="//div[@id='navigation']//a">
<a>
<xsl:attribute name='href'>
<xsl:value-of select='@href' />
</xsl:attribute>
<!-- Change your content here -->
</a>
</xsl:template>
</xsl:stylesheet>