Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Quick Tip on Including JavaScript files in Your Model-Glue Views

DZone's Guide to

Quick Tip on Including JavaScript files in Your Model-Glue Views

· Web Dev Zone ·
Free Resource

Learn how error monitoring with Sentry closes the gap between the product team and your customers. With Sentry, you can focus on what you do best: building and scaling software that makes your users’ lives better.

While programming with Model-Glue, I find that I have to often include JavaScript files in each individual view. I most often do this for form validation but it could be for whatever other reason.  To keep things consistent, my project layout is based on the standard Model-Glue project layout with the editions of "css", "js" and "images":
  • trunk
    • config
    • controller
    • css
    • images
    • js
    • model
    • views

As you might have guessed, all my JavaScript files reside under "js". So until recently, I would include a JavaScript file as follows:

<script language="javascript" type="text/javascript">
<cfinclude template="../js/frmScanBadge.js" />
</script>

While this works, I do not like to have the hard coded path of the file. So instead, I settled on a solution that will get the name of the current view, look for a corresponding JavaScript file under the "js" directory and if finds one, it will include it:

<!--- If a JavaScript file exists with the name of the current template under the /js directory, include it --->
<cfif fileExists(expandPath("js/" & getFileFromPath(getCurrentTemplatePath()).replaceAll(".cfm", ".js")))>
<script language="javascript" type="text/javascript">
<cfinclude template="#'../js/' & getFileFromPath(getCurrentTemplatePath()).replaceAll('.cfm', '.js')#" />
</script>
</cfif>
This solution allows me to keep the name of the view and the corresponding JavaScript file the same. For new views, I can just drop a JavaScript file with the correct name in the "js" directory and it will be included in my view. Not insanely useful but nice non the less.

What’s the best way to boost the efficiency of your product team and ship with confidence? Check out this ebook to learn how Sentry's real-time error monitoring helps developers stay in their workflow to fix bugs before the user even knows there’s a problem.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}