首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 利用模板機制實現多語言切換

     編輯:關於ASP.NET

多語言實現方案眾多,常見的有:VS 資源檔、重寫控件賦值、以及模板替換法。本文介紹一種基於模板與正則替換的輕量級方案。

核心原理

頁面中以 {key} 格式標記多語言佔位符,後端在 Render 階段攔截輸出 HTML,用正則提取所有佔位符,從資源表(可快取)查找對應語言文本並替換,最後寫回響應流。

關鍵命名空間

using System.Text.RegularExpressions;
using System.Text;
using System.IO;
using System.Diagnostics;

核心代碼實現

protected override void Render(HtmlTextWriter writer)
{
    Stopwatch sw = new Stopwatch();
    sw.Start();
    try
    {
        StringBuilder sb = new StringBuilder();
        StringWriter swriter = new StringWriter(sb);
        HtmlTextWriter htw = new HtmlTextWriter(swriter);
        base.Render(htw);
        string content = sb.ToString();

        // 匹配 {xxx} 格式標籤
        Regex re = new Regex(@"{\S+}", RegexOptions.Multiline);
        MatchCollection mc = re.Matches(content);

        // 用 Hashtable 去重並替換
        Hashtable ht = new Hashtable();
        Hashtable resourceHt = GetResourceTable(); // 從快取/資源檔讀取

        foreach (Match m in mc)
        {
            string key = m.Value;
            if (!ht.ContainsKey(key))
            {
                ht.Add(key, null);
                string dictKey = key.Trim('{', '}');
                if (resourceHt.ContainsKey(dictKey))
                {
                    content = content.Replace(key, (string)resourceHt[dictKey]);
                }
            }
        }
        ht.Clear();
        writer.Write(content);
    }
    catch (Exception ex)
    {
        Response.Write(ex.ToString());
        Response.End();
    }
    finally
    {
        sw.Stop();
        Response.Write("runtime:" + sw.ElapsedMilliseconds + "ms");
    }
}

優缺點分析

  • 優點:無需修改現有控件,對舊專案滲透性低;資源集中管理,易維護。
  • 缺點:正則替換在大頁面可能有性能開銷;需確保佔位符格式唯一,避免誤替換。

此法適合中小型專案快速加入多語言支援,大型系統建議採用官方資源檔方案。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved