[英]ASP.NET MVC bundle scripts with translation
根據Nadeem Afana的博客 ,我使用了類似於Mads Kristensen博客的腳本翻譯器對MVC進行了本地化。 問題在於捆綁包是在Application_Start方法中注冊的。 這會導致腳本以一種(默認)語言進行翻譯,並存儲在瀏覽器/服務器緩存中。 改變語言/文化不會產生它們的語言等同性。 是否可以類似於視圖那樣實現緩存配置文件VaryByCustom =“ culture”? 有沒有更好的做法/解決方案? 是否可以將HTML5應用程序緩存與已翻譯的腳本一起使用?
腳本翻譯器類:
public class ScriptTranslator : IBundleTransform {
public ScriptTranslator(ResourceManager manager) {
RM = manager;
}
public void Process(BundleContext context, BundleResponse response) {
response.Content = TranslateScript(response.Content);
}
private static ResourceManager RM;
private static Regex REGEXP = new Regex( @"translate\(""([^\))]*)""\)", RegexOptions.Singleline | RegexOptions.Compiled);
private string TranslateScript(string text) {
MatchCollection matches = REGEXP.Matches(text);
foreach (Match key in matches) {
object obj = RM.GetObject(kay.Groups[1].Value);
if (obj != null) {
text = text.Replace(kay.Value, CleanText(obj.ToString()));
}
}
return text;
}
private static string CleanText(string text) {
return string.Format("\"{0}\"", text.Replace("\\", "\\\\"));
}
}
使用自定義工具名稱空間Resources.Javascript的資源文件; 我的捆綁包配置是:
public class BundleConfig {
public static void RegisterBundles(BundleCollection bundles) {
var DEFAULT_SCRIPT_PATH = "~/Scripts/Modules/";
var DEFAULT_SCRIPT_BOUNDLE_PATH = "~/ScriptBundles/";
var mainBoundle = new ScriptBundle(DEFAULT_SCRIPT_BOUNDLE_PATH + "main")
.Include(DEFAULT_SCRIPT_PATH + "test.js");
mainBoundle.Transforms.Clear();
mainBoundle.Transforms.Add(new ScriptTranslator(Resources.JavaScript.test.ResourceManager));
mainBoundle.Transforms.Add(new JsMinify());
bundles.Add(mainBoundle);
}
}
我們針對此問題的解決方案不僅是通過控制器/動作組合來存儲不同的捆綁軟件,而且還是通過CurrentUICulture來存儲。
string.Format("scriptsDependency{0}{1}_{2}", controler, action, Thread.CurrentThread.CurrentUICulture.Name);
我還建議存儲靜態庫,例如JQuery或Bootstrap。 但是對於動態內容,我建議使用NoCache策略。
public class NonCacheableTransformer : IBundleTransform
{
public void Process(BundleContext context, BundleResponse response)
{
context.UseServerCache = false;
response.Cacheability = HttpCacheability.NoCache;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.