`
raisun_1988
  • 浏览: 114170 次
  • 性别: Icon_minigender_1
  • 来自: 长沙
社区版块
存档分类
最新评论

MonoRail学习笔记二十:资源文件的使用和多语言支持

    博客分类:
  • Java
阅读更多

 

-

和ASP.NET一样,MonoRail也可以方便的使用资源文件,以及利用资源文件来实现多语言的支持。
主要是利用了ResourceLocalizationFilter这两个属性,具体使用方法如下:

1、使用资源文件
Controller代码:

[Resource("resx","TestSiteNVelocity.Controllers.ResourceFile")]
publicclassResourcedController:SmartDispatcherController
{
publicvoidGetResources()
{
}

}
Resource属性第一个参数resx是用来在vm中使用的,第二个参数指定要使用的资源文件的名称,这个例子中使用的是程序集TestSiteNVelocity.Controllers中的ResourceFile文件。

vm代码:
$resx.testKey
然后再加入ResourceFile.resx和ResourceFile.zh-cn.resx两个资源文件,都包含名称为testKey的键值
那么在中文环境下浏览就会显示ResourceFile.zh-cn.resx里面定义的值,在英文或其他环境下浏览时就会显示ResourceFile.resx里面定义的值

另外还可以使用如下方式:
[Resource("resx","TestSiteNVelocity.Controllers.ResourceFile",CultureName="zh-cn")]
来强制指定使用中文的资源文件,即ResourceFile.zh-cn.resx

2、结合LocalizationFilter属性实现多语言
Controller代码:
[Resource("resx","TestSiteNVelocity.Controllers.ResourceFile")]
[LocalizationFilter(Castle.MonoRail.Framework.Filters.RequestStore.Cookie,
"locale")]
publicclassResourcedController:SmartDispatcherController
{
publicvoidGetResources()
{
}


publicvoidSetLanguage(StringlangCode)
{
Response.CreateCookie(
"locale",langCode);

RedirectToAction(
"GetResources");
}

}

vm代码:
$resx.testKey

<formmethod="post"action="SetLanguage.rails"id="form1">
<selectname="langCode"onchange="document.getElementById('form1').submit();">
<optionvalue=""></option>
<optionvalue="zh-cn">中文</option>
<optionvalue="en">English</option>
</select>
</form>

浏览效果如下:

就可以动态的选择语言了
解释:
当选择下拉列表中的一个语言后,调用Controller中的SetLanguage方法,将选择的语言放入cookie中,cookie名为:locale,然后重新进入此页面。进入此页面时由LocalizationFilter属性决定根据cookie中的locale的值来设定当前的本地化。
当然这里LocalizationFilter属性也可以根据SessionCookieQueryStringFormParams中的值来决定本地化

 

 

欢迎加入:http://www.itpob.cn/bbs

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics