結局、ApplicationResources.groovy
プログラムでモジュールを作成する方向に進んだので、カスタムタグでを使用できます<r:require/>
。
アイデアは、バックボーンビューごとに、ファイル内web-app/myApp/views
にバックボーンビューがあり、.js
ファイル内にハンドルバーテンプレートがあり.handlebars
ます(慣例により同じ名前です)。ファイルは通常のモジュールとして宣言され.handlebars
ますが、Handlebars-Resourcesプラグインによってプリコンパイルされます。
の一部のコードは、ApplicationResources.groovy
すべてのビューを検索し、対応するリソースモジュールを作成します。
GrailsApplication grailsApplication = Holders.getGrailsApplication()
File viewsDir = grailsApplication.parentContext.getResource("myApp/views").file;
if (viewsDir.exists() && viewsDir.isDirectory() && viewsDir.canRead()) {
String[] viewsJS = viewsDir.list().findAll { name ->
name.endsWith("View.js")
}
String[] views = viewsJS.collect { name ->
name.substring(0, name.length() - ".js".length())
}
for (view in views) {
"${view}" {
dependsOn 'backbone', 'backbone_relational', 'handlebars'
resource url: "dpg/views/${view}.handlebars",
attrs: [type: 'js'],
disposition: 'head'
resource url: "dpg/views/${view}.js",
disposition: 'head'
}
}
}
次に、taglib:
class ViewsTagLib {
static namespace = "myApp"
def view = { attrs ->
r.require(module: "${attrs.name}View")
out << "<${attrs.tagName} id='${attrs.id}'></${attrs.tagName}>"
}
}
GSPで呼び出す:
<myApp:view tagName="div" name="foo" id="foo1"/>
<myApp:view tagName="div" name="foo" id="foo2"/>
生産:
<html>
<head>
...
<!--
Automagically generated modules (included only once).
Should put these in the same bundle, but handlebars-resources
gets confused.
-->
<script src="/myApp/static/bundle-bundle_fooView_handlebars.js"
type="text/javascript" ></script>
<script src="/myApp/static/bundle-bundle_fooView_head.js"
type="text/javascript" ></script>
</head>
<body>
...
<div id="foo1"></div> <!-- backbone placeholder for 1st view instance-->
<div id="foo2"></div> <!-- backbone placeholder for 2nd view instance-->
</body>
</html>
きれいではありませんが、混乱はほとんど隠されており、定型文や複数のファイルにマジックストリングを追加するのを忘れる機会を大幅に減らす必要があります。