CFLib.org – Common Function Library Project

getRelative(abspath)

Last updated April 9, 2012

Version: 2 | Requires: ColdFusion 5 | Library: FileSysLib

 
Rated 2 time(s). Average Rating: 4.0

Description:
Use getRelative() is the inverse of the ColdFusion native ExpandPath() function -- it takes an absolute file path and returns a relative path to the given file from the current template. As opposed to expandpath(), getRelative() creates a path relative to the current template, not the base template.

Return Values:
Returns a string.

Example:

view plain print about
<cfoutput>#getRelative('d:\temp\test.txt')#</cfoutput>

Parameters:

Name Description Required
abspath Absolute path. Yes

Full UDF Source:

view plain print about
<cfscript>
/**
 * Returns a relative path from the current template to an absolute file path.
 * v2 fix by Tony Monast
 * 
 * @param abspath      Absolute path. (Required)
 * @return Returns a string. 
 * @author Isaac Dealey (info@turnkey.to) 
 * @version 2, April 9, 2012 
 */

function getRelative(abspath) { 
       var currentPath = ListToArray(GetDirectoryFromPath(GetBaseTemplatePath()),"\/");
       var filePath = ListToArray(abspath,"\/");
       var relativePath = ArrayNew(1);
       var pathStart = 0;
       var i = 0;

       /* Define the starting path (path in common) */
       for (i = 1; i LTE ArrayLen(currentPath); i = i + 1) {

               if (currentPath[i] NEQ filePath[i]) {
                       pathStart = i;
                       break;
               }
       }

       /* Build the prefix for the relative path (../../etc.) */
       for (i = ArrayLen(currentPath) - pathStart ; i GTE 0 ; i = i - 1) {
               ArrayAppend(relativePath,"..");
       }

       /* Build the relative path */
       for (i = pathStart; i LTE ArrayLen(filePath) ; i = i + 1) {
               ArrayAppend(relativePath,filePath[i]);
       }

       /* Return the relative path */
       return ArrayToList(relativePath,"/");
}
</cfscript>
blog comments powered by Disqus

Search CFLib.org


Latest Additions

Dave Anderson Dave Anderson added
iniToStruct
20 day(s) ago

Dave Anderson Dave Anderson added
deDupeArray
20 day(s) ago

Richard Richard added
dice
22 day(s) ago

Isaac Dealey Isaac Dealey added
getRelative
a while ago

Top Rated

Darwan Leonardo Sitepu backupDatabase
Rated 5.0, 22 time(s)

Barney Boisvert indentXml
Rated 5.0, 10 time(s)

Kevin Pepperman generateSsccAsn
Rated 5.0, 4 time(s)

Raymond Camden highlightAndCrop
Rated 5.0, 4 time(s)

Created by Raymond Camden / Design by Justin Johnson