0 users online. Create an account or sign in to join them.Users

Author:
mprofitl
Version:
1.0
Release Date:
5 Mar 2016
Category:
String Operations

Description

This utility may be passed an hexadecimal string such as #485EBC and it will return the RGB equivalent (in this case, 72, 94, 188). You may pass an opacity parameter to receive an RGBA string.

Hex values may be supplied both with or without leading # and the utility accepts both lower and upper case.

After importing this template into an xsl stylesheet, you would call the hex-to-rgba template like this:

<xsl:call-template name="rbga-to-hex"/>
    <xsl:with-param name="hex-val" select="#485EBC"/>
</xsl:call-template>

This would output: 72, 94, 188.

Or, for an RGBA string, call the template this way:

<xsl:call-template name="rbga-to-hex">
   <xsl:with-param name="hex-val" select="#485EBC"/>
   <xsl:with-param name="opacity" select="0.8"/>
</xsl:call-template>

It would output 72, 94, 188, 0.8.

XSLT

View Raw
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:template name="hex-to-rgba">
	<xsl:param name="hex-val"/>
	<xsl:param name="opacity"/>

	<xsl:param name="hex" select="translate(translate($hex-val, '#', ''), 'abcdef', 'ABCDEF')"/>
	
	<xsl:variable name="r">
		<xsl:call-template name="hexpairs-to-dec">
			<xsl:with-param name="pair" select="1"/>
			<xsl:with-param name="hex" select="$hex"/>
		</xsl:call-template>
	</xsl:variable>

	<xsl:variable name="g">
		<xsl:call-template name="hexpairs-to-dec">
			<xsl:with-param name="pair" select="2"/>
			<xsl:with-param name="hex" select="$hex"/>
		</xsl:call-template>
	</xsl:variable>

	<xsl:variable name="b">
		<xsl:call-template name="hexpairs-to-dec">
			<xsl:with-param name="pair" select="3"/>
			<xsl:with-param name="hex" select="$hex"/>
		</xsl:call-template>
	</xsl:variable>
	
	<xsl:choose>
		<xsl:when test="string-length($opacity) > 0">
			<xsl:value-of select="concat($r, ', ', $g, ', ', $b, ', ', $opacity)"/>
		</xsl:when>
		<xsl:otherwise>
			<xsl:value-of select="concat($r, ', ', $g, ', ', $b)"/>
		</xsl:otherwise>
	</xsl:choose>
	
</xsl:template>
    
<xsl:template name="hexpairs-to-dec">
	<xsl:param name="pair" select="1"/>
	<xsl:param name="hex"/>
	<xsl:variable name="hex-pair" select="substring($hex,$pair * 2 - 1,2)"/>
	<xsl:if test="$hex-pair">
		<xsl:variable name="hex" select="'0123456789ABCDEF'"/>
		<xsl:value-of select="(string-length(substring-before($hex, substring($hex-pair,1,1))))*16 + string-length(substring-before($hex,substring($hex-pair,2,1)))"/>
	</xsl:if>
</xsl:template>

</xsl:stylesheet>

Discuss this XSLT Utility

Symphony • Open Source XSLT CMS

Server Requirements

  • PHP 5.3-5.6 or 7.0-7.1
  • PHP's LibXML module, with the XSLT extension enabled (--with-xsl)
  • MySQL 5.5 or above
  • An Apache or Litespeed webserver
  • Apache's mod_rewrite module or equivalent

Compatible Hosts

Sign in

Login details