编写 T4 生成的代码来分离输出文件 [英] Write T4 generated code to separate output files

查看:26
本文介绍了编写 T4 生成的代码来分离输出文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个 .tt 文件,用于将文本转换为模型类.

I am creating a .tt file that transforms text into model classes, to practice.

一个 .cs 文件与所有 models 一起生成,但我希望每个 model 都保存在自己的 中.cs 文件位于不同的文件夹中.

A .cs file is generated that with all models, but I would like each model to be saved in its own .cs file in a different folder.

实现这一目标的最佳方法是什么?

What would be the best approach to achieve this?

推荐答案

这里是一个简单的例子,你可以如何从单个 T4 模板输出多个文件.

Here is simple example how you can output multiple files from single T4 template.

使用 SaveOutput 方法输出文件 (Content1.txt,Content2.txt..) 被创建到与 .tt 文件相同的文件夹中,使用 SaveOutputToSubFolder 输出文件进入单独的文件夹 (1\Content1.txt, 2\Content2.txt..)

Using SaveOutput-method output files (Content1.txt,Content2.txt..) are created to same folder than .tt-file, with SaveOutputToSubFolder output files goes to separate folders (1\Content1.txt, 2\Content2.txt..)

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System" #>
<#@ import namespace="System.IO" #>
<#@ output extension=".txt" #>
<#
for (Int32 i = 0; i < 10; ++i) {
#>
File Content <#= i #>
<#

  SaveOutput("Content" + i.ToString() + ".txt");
  //Uncomment following to write to separate folder 1,2,3
  //SaveOutputToSubFolder(i.ToString(),"Content" + i.ToString() + ".txt");
}
#>
<#+
private void SaveOutput(string outputFileName) {
  string templateDirectory = Path.GetDirectoryName(Host.TemplateFile);
  string outputFilePath = Path.Combine(templateDirectory, outputFileName);
  File.WriteAllText(outputFilePath, this.GenerationEnvironment.ToString()); 
  this.GenerationEnvironment.Clear();
}
private void SaveOutputToSubFolder(string folderName, string outputFileName) {
  string templateDirectory = Path.GetDirectoryName(Host.TemplateFile);
  string newDirectoryName = Path.Combine(templateDirectory,folderName);
  if(!Directory.Exists(newDirectoryName))
    Directory.CreateDirectory(newDirectoryName);
  string outputFilePath = Path.Combine(newDirectoryName, outputFileName);
  File.WriteAllText(outputFilePath, this.GenerationEnvironment.ToString()); 
  this.GenerationEnvironment.Clear();
}
#>

这篇关于编写 T4 生成的代码来分离输出文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆