Ask a Jedi: Getting the current directory

I sometimes like to start the morning off with an easy question. Makes me feel all smarty-pants and stuff. Here is a quickie from Patrick that may actually be news to some folks, so hopefully it will be easy for me - helpful for others.

Hi Ray, me again I have a, maybe silly, question about getting the current directory. I have to get the current directory in which a template resides. But I don't want the full path. If i run www.example.com/folder/index.cfm i should get "folder" but not path/to/somewhere/in/the/system/folder. I tried with expandpath("./") and getDirectoryFrom Path(ExpandPath(CGI.SCRIPT_NAME)) but this always returns a full path. Any built in function i forgot to try? Thanks for a hint!

This is two issues here. How do I get the directory from a full path, and how do I get the current directory. The first one is simple. The getDirectoryFromPath() function will take any full path and return just the directory. There is also a corresponding getFileFromPath() function.

The second issue is slightly more complicated. ColdFusion has two functions related to getting the current template. They are getBaseTemplatePath() and getCurrentTemplatePath(). I tend to forget which does what, but consider this first example:

<cffunction name="onRequestStart" returnType="boolean" output="true"> <cfargument name="thePage" type="string" required="true"> <cfoutput> getCurrentTemplatePath()=#getCurrentTemplatePath()#<br> getBaseTemplatePath()=#getBaseTemplatePath()#<br> <p> </cfoutput> <cfreturn true> </cffunction>

When I run test4.cfm, I get:

getCurrentTemplatePath()=/Users/ray/Documents/Web Sites/webroot/Application.cfc
getBaseTemplatePath()=/Users/ray/Documents/Web Sites/webroot/test4.cfm

The getCurrentTemplatePath refers to the actual file being run right now, which is Application.cfc, and getBaseTemplatePath returns to the main file being executed.

If that sounds a bit unclear, forgive me. As I said, I always forget the difference (one reason I’ll fail the CF8 cert probably). In general you are going to want to use getCurrentTemplatePath if you want to consider the file where the actual function is being run.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Comments