ロケール対応プラグインを作ってみる[追記](Grails 0.5)
トップページ(index.gsp)のロケール対応もやってみたので追記!なお、以下の処理に対しての追記があるので注意。
プロジェクトディレクトリ配下の、src/java/jp/ne/hatena/d/noryksj/grails/pluginsに以下のようなソースを作成。
package jp.ne.hatena.d.noryksj.grails.plugins; import java.util.Locale; import org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.core.io.Resource; /** * Lcale aware GroovyPagesTemplateEngine * @author noryksj */ public class LocaledTemplateEngine extends GroovyPagesTemplateEngine { /** {@inheritDoc} */ public Resource getResourceForUri(String uri) { int lastSlash = uri.lastIndexOf('/'); int lastDot = uri.lastIndexOf('.'); if (lastSlash < 0) { lastSlash = 0; } if (lastDot > lastSlash) { Locale locale = LocaleContextHolder.getLocale(); String checkUri = uri.substring(0, lastDot) + "_" + locale.getLanguage() + uri.substring(lastDot); Resource res = super.getResourceForUri(checkUri); if (res != null && res.exists()) { return res; } } return super.getResourceForUri(uri); } }
LocaleContextHolder.getLocale()でロケールを取るのは苦肉の策で。で、LocaleViewSwitcherGrailsPlugin.groovyファイルのdoWithSpringクロージャを以下のように修正。
def doWithSpring = { groovyPagesTemplateEngine(LocaledTemplateEngine) { classLoader = ref("classLoader") if(grails.util.GrailsUtil.isDevelopmentEnv()) { resourceLoader = groovyPageResourceLoader } } jspViewResolver(LocaledViewResolver) { viewClass = org.springframework.web.servlet.view.JstlView.class prefix = GrailsApplicationAttributes.PATH_TO_VIEWS suffix = ".jsp" templateEngine = groovyPagesTemplateEngine if(grails.util.GrailsUtil.isDevelopmentEnv()) { resourceLoader = groovyPageResourceLoader } } }
再度、プラグインをパッケージして、別のGrailsプロジェクトに再度インストールする。その際、grails cleanを実行してから、plugins/LocaleViewSwitcher-0.1をディレクトリごと削除してから行う。でないと、実行時にZIPファイルが読めないとかわけのわからないエラーが出る(というか出た)。
index_ja.gspを作成して実行すると、できた!!
他にも手を入れないといけない箇所があるやも。それは気が付いたときにすることにする。本当にやりたいことにはまだまだ足りないのだ。
ここにいたって疑問がひとつ。index_ja.gspとかを作ってプロパティファイルとか関係なしにガンガン日本語を書けるのだけれど、index_ja.gspの文字コードは何で作ればいいんだろう?どうもデフォルトのキャラクタセットでGSPファイルを読んでいるようだけど、UTF-8とかで書きたいなぁ。でないと、Windowsで開発したアプリをLinuxで実行すると・・・怖いことになりそう。