javascript
Purpose
Allows inclusion of javascript libraries and scripts as well a shorthand for inline JavascriptExamples
// actually imports '/app/js/myscript.js'
<g:javascript src="myscript.js" />// imports all the necessary js for the scriptaculous library
<g:javascript library="scripaculous" /><g:javascript>alert('hello')</g:javascript>
Description
Attributes
-
library
(optional) - The name of the library to include. Either "prototype", "scriptaculous", "yahoo" or "dojo"
-
src
(optional) - The name of the javascript file to import. Will look in /app/js dir
-
base
(optional - Since 0.6) - specifies the full base url to prepend to the library name
Source
Show Source
def javascript = { attrs, body ->
setUpRequestAttributes();
def requestPluginContext = request[CONTROLLER]?.pluginContextPath
if(attrs.src) {
javascriptInclude(attrs)
}
else if(attrs.library) { if(LIBRARY_MAPPINGS.containsKey(attrs.library)) {
if(!request[INCLUDED_LIBRARIES].contains(attrs.library)) {
LIBRARY_MAPPINGS[attrs.library].each {
if(!request[INCLUDED_JS].contains(it)) {
request[INCLUDED_JS] << it
def newattrs = [:] + attrs
newattrs.src = it+'.js'
javascriptInclude(newattrs)
}
}
request[INCLUDED_LIBRARIES] << attrs.library
}
}
else {
if(!request[INCLUDED_LIBRARIES].contains(attrs.library)) {
def newattrs = [:] + attrs
newattrs.src = newattrs.remove('library')+'.js'
javascriptInclude(newattrs)
request[INCLUDED_LIBRARIES] << attrs.library
request[INCLUDED_JS] << attrs.library
}
}
}
else {
out.println '<script type="text/javascript">'
out.println body()
out.println '</script>'
}
} private javascriptInclude(attrs) {
def requestPluginContext = request[CONTROLLER]?.pluginContextPath
out << '<script type="text/javascript" src="'
if (!attrs.base) {
def baseUri = grailsAttributes.getApplicationUri(request)
out << baseUri
out << (baseUri.endsWith('/') ? '' : '/')
out << (requestPluginContext ? "${requestPluginContext}/" : "")
out << 'js/'
} else {
out << attrs.base
}
out << attrs.src
out.println '"></script>'
}