次の方法で共有


テキスト テンプレートから Visual Studio またはその他のホストにアクセスする

テキスト テンプレートでは、テンプレートを実行するホストによって公開されているメソッドとプロパティを使用できます。 ホストの 1 つの例が、Visual Studio です。

注意

ホスト メソッドとプロパティは、通常のテキスト テンプレートでは使用できますが、前処理されたテキスト テンプレートでは使用できません。

ホストへのアクセスを取得する

ホストにアクセスするには、template ディレクティブで hostspecific="true" を設定します。 これで、型 ITextTemplatingEngineHost を持つ this.Host を使用できるようになりました。 ITextTemplatingEngineHost 型には、たとえばファイル名を解決し、エラーをログするために使用できるメンバーがあります。

ファイル名を解決する

テキスト テンプレートを基準としたファイルの完全なパスを検索するには、this.Host.ResolvePath() を使用します。

<#@ template hostspecific="true" language="C#" #>
<#@ output extension=".txt" #>
<#@ import namespace="System.IO" #>
<#
 // Find a path within the same project as the text template:
 string myFile = File.ReadAllText(this.Host.ResolvePath("MyFile.txt"));
#>
Content of myFile is:
<#= myFile #>

エラー メッセージを表示する

この例では、テンプレートを変換するときにメッセージをログします。 ホストが Visual Studio の場合は、エラーがエラー一覧に追加されます。

<#@ template hostspecific="true" language="C#" #>
<#@ output extension=".txt" #>
<#@ import namespace="System.CodeDom.Compiler" #>
<#
  string message = "test message";
  this.Host.LogErrors(new CompilerErrorCollection()
    { new CompilerError(
       this.Host.TemplateFile, // Identify the source of the error.
       0, 0, "0",   // Line, column, error ID.
       message) }); // Message displayed in error window.
#>

Visual Studio API を使用する

Visual Studio でテキスト テンプレートを実行している場合は、this.Host を使用して、Visual studio によって提供されるサービスと読み込まれたあらゆるパッケージまたは拡張機能にアクセスできます。

hostspecific="true" に設定し、this.HostIServiceProvider にキャストします。

この例では、Visual Studio API、DTE をサービスとして取得します。

<#@ template hostspecific="true" language="C#" #>
<#@ output extension=".txt" #>
<#@ assembly name="EnvDTE" #>
<#@ import namespace="EnvDTE" #>
<#
 IServiceProvider serviceProvider = (IServiceProvider)this.Host;
 DTE dte = serviceProvider.GetService(typeof(DTE)) as DTE;
#>
Number of projects in this solution: <#=  dte.Solution.Projects.Count #>

テンプレートの継承で hostSpecific を使用する

inherits 属性も使用し、hostspecific="true" を指定するテンプレートから継承する場合は hostspecific="trueFromBase" を指定します。 そうしないと、プロパティ Host が 2 回宣言されていることを示すコンパイラの警告が表示されることがあります。