HTML Tags in XSLT Variables

Sometimes there is the need to show text inside HTML tags. For instance, in one occasion, I wanted to show just a portion of the contents in a Wiki field, but just the text. xsl:value-of will return the contents inside HTML tags:

   1: <xsl:variable name="html">
   2:     This <div style="something"><span>is some</span> HTML <strong>contents</strong></div>
   3: </xsl:variable>
   4:  
   5: <xsl:value-of select="$html"/>

This will return This is some HTML contents.

If in the other hand you want to show the HTML contents as is, use xsl:copy-of instead:

   1: <xsl:copy-of select="$html"/>

Which will return “This

is some HTML contents” (line break because of the DIV element).

However, if your variable is HTML encoded (> are &gt;, < are &lt;, etc), it’s a whole different matter. For that, you need to use a recursive template:

   1: <xsl:template name="StripHtml">
   2:     <xsl:param name="html"/>
   3:     <xsl:choose>
   4:         <xsl:when test="contains($html, '&amp;lt;')">
   5:             <xsl:value-of select="substring-before($html, '&amp;lt;')"/>
   6:             <xsl:call-template name="StripHtml">
   7:                 <xsl:with-param name="html" select="substring-after($html, '&amp;gt;')"/>
   8:             </xsl:call-template>
   9:         </xsl:when>
  10:         <xsl:otherwise>
  11:             <xsl:value-of select="$html"/>
  12:         </xsl:otherwise>
  13:     </xsl:choose>
  14: </xsl:template>
  15:  
  16: <xsl:variable name="html_encoded">
  17:     This &amp;lt;div&amp;gt;&amp;lt;span&amp;gt;is some&amp;lt;/span&amp;gt; HTML &amp;lt;strong&amp;gt;contents&amp;lt;/strong&amp;gt;&amp;lt;/div&amp;gt;
  18: </xsl:variable>
  19:  
  20: <xsl:call-template name="StripHtml">
  21:     <xsl:with-param name="html" select="$html_encoded"/>                
  22: </xsl:call-template>

Will return This is some HTML contents as well. The logic is this:

  1. First, show anything before the first < (&lt;), if it exists;
  2. Check if the parameter contains a <, and if so, call the template recursively passing as a parameter the text after > (&gt;), which is supposed to exist;
  3. Otherwise, just output the parameter.

                             

No Comments

Add a Comment

As it will appear on the website

Not displayed

Your website