Thursday, April 10, 2008

Macro for HTML encoding fields in templates

In Umbraco when you try to add a field to your template you can UrlEncode it like this :
<?UMBRACO_GETITEM field="MyField" urlEncode="true" />

But you can't do this :
<?UMBRACO_GETITEM field="MyField"  htmlEncode="true" />

I read in this forum thread that a fix for this has been submitted to codeplex but untill it's released I have made a macro to work around this.

First create a XSLT file and call it HTMLEncode and check the box "Create macro"

Then paste the following code in to your macro :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xsl:Stylesheet [ &lt;!ENTITY nbsp "&#x00A0;"> ]>
<xsl:stylesheet 
    version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:msxml="urn:schemas-microsoft-com:xslt"
    xmlns:umbraco.library="urn:umbraco.library"
    exclude-result-prefixes="msxml umbraco.library">


<xsl:output method="xml" omit-xml-declaration="yes"/>

<xsl:param name="currentPage"/>

<xsl:param name="field" select="/macro/field" />

<xsl:template match="/">

<!-- start writing XSLT -->
<xsl:if test="$field">
    <xsl:value-of select="$currentPage/data[@alias=$field]"/>
</xsl:if>
</xsl:template>

</xsl:stylesheet>

Then go to your macro and add a parameter called field of the type propertyTypePicker

In your templates you can now use this macro to htmlencode fields.

I hope you can use it.

Next blog will be about importing node with the webservices API.

1 comment:

Anonymous said...

Hi Dave,

We finaly have a date and venue for the first umbraco meeting in Belgium. So if you would like to join, just let us know.

http://www.umbraco.org/blog/2008/6/23/belgian-umbraco-meet-up-on-july-19th