Phanix
Phanix

Just writing

Using T4 template to read resource files (.resx) and generate multiple output files

T4 (Text Template Transformation Toolkit) 可以幫忙訂出 template 並用程式輔助來產生程式碼或文件(比方說不同語言的定義檔)。

使用 T4 之前可以先去下載 T4 Toolbox,安裝之後在 Visual studio 增加新項目時就可以看到有 “T4 Toolbox” 的分類,有 Generator、Script、Template 三種可選

首先定義template檔案,在這邊用System.Xml去讀取 resource file,同時 include SaveOutput.tt 做輸出用。

<#@ template language="C#" debug="True" #>
<#@ include file="SaveOutput.tt" #>
<#@ include file="T4Toolbox.tt" #>
<#@ assembly name="System.Xml" #>
<#@ import namespace="System.Xml" #>
<#
// <copyright file="i18n_js.tt" company="Onelab">
//  Copyright © Onelab. All Rights Reserved.
// </copyright>

string[] files = System.IO.Directory.GetFiles(this.Host.ResolvePath("..\\App_GlobalResources"));
string outputFileLang = "";

foreach (string f in files) {
	if (f.Substring(f.Length-4) != "resx"){
		continue;
	}

	XmlDocument xd = new XmlDocument();
	xd.Load(f);


	if (f.LastIndexOf("Resource") + 8 == f.LastIndexOf(".")) {
		outputFileLang = "en-Us";
	}
	else
	{
		outputFileLang = f.Substring(f.LastIndexOf("Resource") + 9, f.LastIndexOf(".") - f.LastIndexOf("Resource") - 9);
	}


	foreach (XmlNode node in xd.SelectNodes("//data")) {
		try
		{
#>
			<#=node.Attributes[0].Value#> = <#=node.SelectNodes("value")[0].InnerXml#>;
<#
		}
		catch
		{
		}
	}

	SaveOutput("lang\\" + outputFileLang + ".js");
}
#>

另外定義 SaveOutput function於另一個檔案SaveOutput.tt中

<#@ import namespace="System.IO" #>
<#+
  void SaveOutput(string outputFileName)
  {
      string templateDirectory = Path.GetDirectoryName(Host.TemplateFile);
      string outputFilePath = Path.Combine(templateDirectory, outputFileName);
      File.WriteAllText(outputFilePath, this.GenerationEnvironment.ToString()); 

      this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length);
  }
#>

當resource file變動後,必須要執行”Run Custom Tool”才會更新輸出的檔案內容。

Other resources: Oleg Sych’s article

CC BY-NC-ND 2.0 版权声明

喜欢我的文章吗?
别忘了给点支持与赞赏,让我知道创作的路上有你陪伴。

加载中…

发布评论