我正在为 grails 中的 DateTime 选择器制作自定义 TagLib。代码如下:
class jqueryDateTimePickerTagLib {
def dateTimePicker = {attrs, body ->
def out = out
def name = attrs.name //The name attribute is required for the tag to work seamlessly with grails
def id = attrs.id ?: name
def value = attrs.value ?: new Date().format("yyyy/MM/dd HH:mm")
//Create input data text field for contaning Date Time string
out.println "<input type=\"text\" name=\"${name}\" id=\"${id}\" value=\"${value}\" ><img id=\"${id}opencalender\" src=\"${resource(dir:'images', file:'calendar_btn.png')}\"></input>"
// Adding Resources
out.println "<link rel=\"stylesheet\" href=\"${resource(dir:'css', file:'jquery.datetimepicker.css')}\" />"
out.println "<script src=\"${resource(dir:'js/jquery', file:'jquery.js')}\"></script>"
out.println "<script src=\"${resource(dir:'js/jquery/ui', file:'jquery.datetimepicker.js')}\"></script>"
// java script code
out.println "<script>"
out.println "\$('#${id}').datetimepicker({"
out.println "});"
out.println "\$('#${id}opencalender').click(function(){"
out.println "\$('#${id}').datetimepicker('show');"
out.println "});"
out.println "</script>"
}
}
问题出现在我添加 JQuery 文件资源的地方。当此自定义 DateTime 选择器在 GSP 表单中包含两次时,会导致为每个包含多次声明 JQuery 资源。我看到了一些TagLibs的例子,在那些TagLibs中,JQuery文件资源被添加到不同的def中,如下:
def resources = { attrs ->
String style = attrs.style ? "${attrs.remove('style')}" : null;
String theme = attrs.theme ? "css/${attrs.remove('theme')}.css" : "css/tiger.css";
String lang = attrs.lang ? "calendar-${attrs.remove('lang')}.js" : "calendar-en.js";
if(style) {
out << "<style type='text/css'>@import url(${style});</style>"
} else {
out << "<style type='text/css'>@import url(${resource(dir:pluginContextPath,file:theme)});</style>"
}
out << """
<script type="text/javascript" src="${resource(dir:pluginContextPath,file:"js/calendar.js")}"></script>\n
<script type="text/javascript" src="${resource(dir:pluginContextPath,file:"js/lang/$lang")}"></script>\n
<script type="text/javascript" src="${resource(dir:pluginContextPath,file:"js/calendar-setup.js")}"></script>\n
"""
}
我还尝试在我的自定义 TagLib 中以上述方式包含资源,但没有成功。所以请告诉我解决这个问题的方法。
谢谢。