Welcome 微信登录

首页 / 网页编程 / ASP.NET / ASP.NET中利用模板机制实现多语言

ASP.NET中利用模板机制实现多语言2010-11-05陶刚多语言实现方法有许多种,

1.利用VS2005自带的资源文件去实现

2.重写控件,给多语言赋值<myui:Lable key="language" runat=server />;

3.利用模板,内文格式如<input type="button" value="{search}" />

。。。

以下利用模板机制实现多语言:

原理是用正则式把所有的{XXX}读取出来,然后替换,再写回到页面。

需要用到的命名空间:

using System.Text.RegularExpressions;

using System.Text;

using System.IO;

using System.Diagnostics;

具体代码如下:

[copy to clipboard]

CODE:

protected override void Render(HtmlTextWriter writer)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Reset();
stopwatch.Start();
try
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htw = new HtmlTextWriter(sw);
base.Render(htw);
string content = sb.ToString();
//模板标签{yes},{no},{search}
Regex re = new Regex(@"{S+}", RegexOptions.Multiline);
MatchCollection mc = re.Matches(content);
//利用Hashtable来筛选所有的多语言标签,然后做替换
Hashtable ht = new Hashtable();
//多的资源文件读取到一个Hashtable里,可以保存到缓存里,
Hashtable ResurceHt = new Hashtable();
for (int i = 0; i < mc.Count; i++)
{
if (!ht.ContainsKey(mc.Value))
{
ht.Add(mc.Value, null);
//进行替换
content = content.Replace(mc.Value, (string)ResurceHt[mc.Value.TrimStart("{").TrimEnd("}")]);
}
}
ht.Clear();
//重新写入页面
writer.Write(content);
}
catch (Exception ex)
{
Response.Write(ex.ToString());
Response.End();
}
finally {
stopwatch.Stop();
Response.Write("runtime:" + stopwatch.ElapsedMilliseconds.ToString() + "ms");
}
}