[CODE Smith]调用子模板
2008-02-19 15:14 Jaypei 阅读(515) 评论(0) 编辑 收藏 举报调用子模板,并配置子模板中的参数。
<%@ CodeTemplate Language="C#" TargetLanguage="Text" Description="Transfer cst file." %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Assembly Name="SchemaExplorer.SqlSchemaProvider" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Assembly Name="SchemaExplorer.SqlSchemaProvider" %>
<%@ Import Namespace="SchemaExplorer" %>
使用CodeSmith.Engine.CodeTemplate定义子模板和一个保持唯一对象的访问属性
private CodeTemplate _mySubTemplate;
[Browsable(false)]
public CodeTemplate MySubTemplate
{
get
{
if(_mySubTemplate == null)
{
CodeTemplateCompiler compiler = new CodeTemplateCompiler(this.CodeTemplateInfo.DirectoryName + "UseSubTemplate_sub.cst");
compiler.Compile();
if(compiler.Errors.Count==0)
{
_mySubTemplate = compiler.CreateInstance();
}
else
{
for(int i=0; i<compiler.Errors.Count; i++)
{
this.Response.WriteLine(compiler.Errors[i].ToString());
}
}
}
return _mySubTemplate;
}
}
[Browsable(false)]
public CodeTemplate MySubTemplate
{
get
{
if(_mySubTemplate == null)
{
CodeTemplateCompiler compiler = new CodeTemplateCompiler(this.CodeTemplateInfo.DirectoryName + "UseSubTemplate_sub.cst");
compiler.Compile();
if(compiler.Errors.Count==0)
{
_mySubTemplate = compiler.CreateInstance();
}
else
{
for(int i=0; i<compiler.Errors.Count; i++)
{
this.Response.WriteLine(compiler.Errors[i].ToString());
}
}
}
return _mySubTemplate;
}
}
使用SetProperty(string name,object value)设置子模板属性
public void OutputSubTemplate()
{
string ConnectionString = "...";
// 传递string
MySubTemplate.SetProperty("gString", "String argument.");
// 传递Bool
MySubTemplate.SetProperty("gBool", true);
// 传递Table
DatabaseSchema database = new DatabaseSchema(new SqlSchemaProvider(), ConnectionString);
TableSchema table = database.Tables["TableName"];
MySubTemplate.SetProperty("SourceTable", table);
//...
MySubTemplate.Render(this.Response);
}
{
string ConnectionString = "...";
// 传递string
MySubTemplate.SetProperty("gString", "String argument.");
// 传递Bool
MySubTemplate.SetProperty("gBool", true);
// 传递Table
DatabaseSchema database = new DatabaseSchema(new SqlSchemaProvider(), ConnectionString);
TableSchema table = database.Tables["TableName"];
MySubTemplate.SetProperty("SourceTable", table);
//...
MySubTemplate.Render(this.Response);
}
参考TerryLee的《CodeSmith开发资料.pdf》