Diazo

Adding an attribute to elements

«  Insert wrapping element   ::   Contents   ::   Modifying an attribute  »

Adding an attribute to elements

This recipe demonstrates adding a target attribute to any a (link) tags on a page. This recipe will also ensure that any children elements of the given a tag will be maintained (such as img tags, as shown) and that if said attribute is already set, its value will be maintained. Note that due to processing, the attribute’s ordering on the tag may change.

Rules

<?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">

    <replace css:theme="#target" css:content="#content" />

    <xsl:template match="a">
        <xsl:copy>
            <xsl:attribute name="target">_blank</xsl:attribute>
            <xsl:copy-of select="@*" />
            <xsl:apply-templates />
        </xsl:copy>
    </xsl:template>

</rules>

Theme

<div id="target">
    <div>Content</div>
</div>

Content

<div id="content">
    <!-- This link gets target="_blank" -->
    <a href="http://plone.org" class="my-link">Visit plone.org</a>

    <!-- This link gets target="_blank"-->
    <a href="http://diazo.org" id="diazo-link">Visit diazo.org today!
        <img src="http://docs.diazo.org/en/latest/_images/diazo-concept.png" />
    </a>

    <!-- This link has its target attribute maintained -->
    <a href="http://diazo.org" target="_top">Open in this window</a>
</div>

Output

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <body>
    <div id="content">
    <!-- This link gets target="_blank" -->
    <a target="_blank" href="http://plone.org" class="my-link">Visit plone.org</a>

    <!-- This link gets target="_blank"-->
    <a target="_blank" href="http://diazo.org" id="diazo-link">Visit diazo.org today!
        <img src="http://docs.diazo.org/en/latest/_images/diazo-concept.png" /></a>

    <!-- This link has its target attribute maintained -->
    <a target="_top" href="http://diazo.org">Open in this window</a>
</div>
  </body>
</html>

«  Insert wrapping element   ::   Contents   ::   Modifying an attribute  »