您的位置:首页 > 其它

StringTemplate.net模板技术用法

2008-12-26 10:15 363 查看
using System;
using System.Collections.Generic;
using System.Text;
using Antlr.StringTemplate;
using Antlr.StringTemplate.Language;
using System.IO;
using System.Collections;
using System.Collections.Specialized;

namespace TemplateExplame
{
class Program
{
static void Main(string[] args)
{
//简单变量替换();
//复杂变量替换();
//对象变量替换();
//键值类型替换();
//自定义集合替换();
//同时显示多个变量();
//模板调用();
//给调用模板传参数();
//值模板();
//简单循环();
//交差循环显示();
//通过模板交差循环();
//条件判断();
//从文件中创建模板();

}

#region "变量处理"
private static void 简单变量替换()
{
StringTemplate st = new StringTemplate("简单变量替换 $Text$,真的啊!");
st.SetAttribute("Text", "中华人民共和国");
Console.WriteLine(st.ToString());
}

private static void 复杂变量替换()
{
StringTemplate st = new StringTemplate("复杂变量替换 $Text;null=/"为空值/",separator=/",/"$ 真是复杂啊!");
st.SetAttribute("Text", "中国",null,"台湾","印度");
Console.WriteLine(st.ToString());
}

/// <summary>
/// 如果对象的字段名中有保留字,请用对象名.("变量名")来进行访问.
/// </summary>
private static void 对象变量替换()
{
StringTemplate st = new StringTemplate("对象变量替换 姓名:$User.Name$, 年龄:$User.Age$ ");
User us = new User();
us.Name = "张三";
us.Age = "30";
st.SetAttribute("User", us);
Console.WriteLine(st.ToString());
}

private static void 键值类型替换()
{
StringTemplate st = new StringTemplate("对象变量替换 姓名:$KeyList.Name$, 年龄:$KeyList.Age$ ");
Hashtable ht = new Hashtable();
ht.Add("Name", "李四");
ht.Add("Age", "35");
st.SetAttribute("KeyList", ht);
Console.WriteLine(st.ToString());
}

private static void 自定义集合替换()
{
StringTemplate st = new StringTemplate("自定义集合替换 $List:{姓名:$it.Name$ 年龄:$it.Age$}$");
st.SetAttribute("List.{Name,Age}", "王二", "29");
Console.WriteLine(st.ToString());
}

private static void 同时显示多个变量()
{
StringTemplate st = new StringTemplate("变量相加 $[Temp1,Temp2,Temp3]$");
//StringTemplate st = new StringTemplate("变量相加 $[Temp1,Temp2,Temp3];separator=/",/"$");
st.SetAttribute("Temp1", "变量1");
st.SetAttribute("Temp2", "变量2");
st.SetAttribute("Temp3", "变量3");
Console.WriteLine(st.ToString());
}

#endregion

#region "模板应用"
/// <summary>
/// 模板要相互调用,必需将要调用的模板放入同一个模板组里,才能相互调用.
/// </summary>
private static void 模板调用()
{
StringTemplateGroup sg = new StringTemplateGroup("GroupTest");
sg.DefineTemplate("Box", "中华人民共和国中华人民共和国,中华人民共和国");
StringTemplate st = sg.DefineTemplate("List", "下面是我调用Box模板内容:/n$Box()$");
Console.WriteLine(st.ToString());
}

/// <summary>
/// 参数可以为值,变量,模板
/// </summary>
private static void 给调用模板传参数()
{
StringTemplateGroup sg = new StringTemplateGroup("GroupTest");
sg.DefineTemplate("BoxA", "我不来了()");
sg.DefineTemplate("Box", "中华人民共和国,中华全国 Title: $Title$ !!");
StringTemplate st = sg.DefineTemplate("List", "下面是我调用Box模板内容:/n$Box(Title=/"标题值/")$"); //传变量值
//StringTemplate st = sg.DefineTemplate("List", "下面是我调用Box模板内容:/n$Box(Title={$Titles$})$"); //传变量
//StringTemplate st = sg.DefineTemplate("List", "下面是我调用Box模板内容:/n$Box(Title=BoxA())$"); //传模板
st.SetAttribute("Titles", "标题参数值");
Console.WriteLine(st.ToString());
}

private static void 值模板()
{
StringTemplateGroup sg = new StringTemplateGroup("GroupTest");
sg.DefineTemplate("Box", "中华人民共和国,,,,");
StringTemplate st = new StringTemplate(sg, "调用值模板$Mys:Box();separator=/"==/"$------s");
st.SetAttribute("Mys", "中国");
st.SetAttribute("Mys", "中国");
Console.WriteLine(st.ToString());
}

#endregion

#region "循环显示"
private static void 简单循环()
{
StringTemplate st = new StringTemplate("<table>$Item:{<tr><td>$it$要循环显示的内容</td></tr>}$</table>");
for (int i = 0; i < 10; i++)
{
st.SetAttribute("Item", i);
}
Console.WriteLine(st.ToString());
}

private static void 交差循环显示()
{
User us = new User();
us.Name = "张三";
us.Age = "23";
List<User> uss = new List<User>();
uss.Add(us);
uss.Add(us);
uss.Add(us);
uss.Add(us);
uss.Add(us);
StringTemplate st = new StringTemplate("<table>$Item:{<tr class=black><td>$it.Name$</td></tr>},{<tr class=red><td>$it.Age$</td></tr>};separator=/"/n/"$</table>");
st.SetAttribute("Item", uss);
Console.WriteLine(st.ToString());
}

private static void 通过模板交差循环()
{
User us = new User();
us.Name = "张三";
us.Age = "23";
List<User> uss = new List<User>();
uss.Add(us);
uss.Add(us);
uss.Add(us);
uss.Add(us);
uss.Add(us);

StringTemplateGroup sg = new StringTemplateGroup("GroupTest");
sg.DefineTemplate("RowRed", "<tr class=red><td>$it.Name$</td><td>$it.Age$</td></tr>/n");
sg.DefineTemplate("Rowblack", "<tr class=black><td>$it.Name$</td><td>$it.Age$</td></tr>/n");
StringTemplate st = sg.DefineTemplate("List", "<table>$Item:RowRed(),Rowblack()$</table>");
st.SetAttribute("Item", uss);
Console.WriteLine(st.ToString());

}

#endregion

#region "条件判断"
private static void 条件判断()
{
StringTemplate st = new StringTemplate("当前用户登陆状态: $if(IsAdmin)$ 用户登陆成功! $else$ 用户没有登陆! $endif$");
st.SetAttribute("IsAdmin", true);
Console.WriteLine(st.ToString());
}
#endregion

private static void 从文件中创建模板()
{
StringTemplateGroup group = new StringTemplateGroup("myGroup", new LoadFileHtm(AppDomain.CurrentDomain.BaseDirectory+@"Template/") , typeof(DefaultTemplateLexer));

StringTemplate helloAgain = group.GetInstanceOf("homepage");

helloAgain.SetAttribute("title", "Welcome To StringTemplate");
helloAgain.SetAttribute("name", "World");
helloAgain.SetAttribute("friends", "Terence");
helloAgain.SetAttribute("friends", "Kunle");
helloAgain.SetAttribute("friends", "Micheal");
helloAgain.SetAttribute("friends", "Marq");

Console.WriteLine(helloAgain.ToString());
}

}

public class LoadFileHtm : StringTemplateLoader
{
/// <summary>
/// How are the files encoded (ascii, UTF8, ...)? You might want to read
/// UTF8 for example on a ascii machine.
/// </summary>
private Encoding encoding;

private FileSystemWatcher filesWatcher;
private HybridDictionary fileSet;

public LoadFileHtm()
: this(null, Encoding.Default, true)
{
}

public LoadFileHtm(string locationRoot)
: this(locationRoot, Encoding.Default, true)
{
}
public LoadFileHtm(string locationRoot, bool raiseExceptionForEmptyTemplate)
: this(locationRoot, Encoding.Default, raiseExceptionForEmptyTemplate)
{
}

public LoadFileHtm(string locationRoot, Encoding encoding)
: this(locationRoot, encoding, true)
{
}

public LoadFileHtm(string locationRoot, Encoding encoding, bool raiseExceptionForEmptyTemplate)
: base(locationRoot, raiseExceptionForEmptyTemplate)
{
if ((locationRoot == null) || (locationRoot.Trim().Length == 0))
{
this.locationRoot = AppDomain.CurrentDomain.BaseDirectory;
}
this.encoding = encoding;
fileSet = new HybridDictionary(true);
}

/// <summary>
/// Determines if the specified template has changed.
/// </summary>
/// <param name="templateName">template name</param>
/// <returns>True if the named template has changed</returns>
public override bool HasChanged(string templateName)
{
//string templateLocation = Path.Combine(LocationRoot, GetLocationFromTemplateName(templateName));
string templateLocation = string.Format("{0}/{1}", LocationRoot, GetLocationFromTemplateName(templateName)).Replace('//', '/');
object o = fileSet[templateLocation];
if ((o != null))
{
return true;
}
return false;
}

/// <summary>
/// Loads the contents of the named StringTemplate.
/// </summary>
/// <param name="templateName">Name of the StringTemplate to load</param>
/// <returns>
/// The contexts of the named StringTemplate or null if the template wasn't found
/// </returns>
/// <exception cref="TemplateLoadException">Thrown if error prevents successful template load</exception>
protected override string InternalLoadTemplateContents(string templateName)
{
string templateText = null;
string templateLocation = null;

try
{
//templateLocation = Path.Combine(LocationRoot, GetLocationFromTemplateName(templateName));
templateLocation = string.Format("{0}/{1}", LocationRoot, GetLocationFromTemplateName(templateName)).Replace('//', '/');
StreamReader br;
try
{
br = new StreamReader(templateLocation, encoding);
}
catch (FileNotFoundException)
{
return null;
}
catch (DirectoryNotFoundException)
{
return null;
}
catch (Exception ex)
{
throw new TemplateLoadException("Cannot open template file: " + templateLocation, ex);
}

try
{
templateText = br.ReadToEnd();
if ((templateText != null) && (templateText.Length > 0))
{
//templateText = templateText.Trim();

if (filesWatcher == null)
{
filesWatcher = new FileSystemWatcher(LocationRoot, "*.htm");
//filesWatcher.InternalBufferSize *= 2;
filesWatcher.NotifyFilter =
NotifyFilters.LastWrite
| NotifyFilters.Attributes
| NotifyFilters.Security
| NotifyFilters.Size
| NotifyFilters.CreationTime
| NotifyFilters.DirectoryName
| NotifyFilters.FileName;
filesWatcher.IncludeSubdirectories = true;
filesWatcher.Changed += new FileSystemEventHandler(OnChanged);
filesWatcher.Deleted += new FileSystemEventHandler(OnChanged);
filesWatcher.Created += new FileSystemEventHandler(OnChanged);
filesWatcher.Renamed += new RenamedEventHandler(OnRenamed);
filesWatcher.EnableRaisingEvents = true;
}
}
fileSet.Remove(templateLocation);
}
finally
{
if (br != null) ((IDisposable)br).Dispose();
br = null;
}
}
catch (ArgumentException ex)
{
string message;
if (templateText == null)
message = string.Format("Invalid file character encoding: {0}", encoding);
else
message = string.Format("The location root '{0}' and/or the template name '{1}' is invalid.", LocationRoot, templateName);

throw new TemplateLoadException(message, ex);
}
catch (IOException ex)
{
throw new TemplateLoadException("Cannot close template file: " + templateLocation, ex);
}
return templateText;
}

/// <summary>
/// Returns the location that corresponds to the specified template name.
/// </summary>
/// <param name="templateName">template name</param>
/// <returns>The corresponding template location or null</returns>
public override string GetLocationFromTemplateName(string templateName)
{
return templateName + ".htm";
}

/// <summary>
/// Returns the template name that corresponds to the specified location.
/// </summary>
/// <param name="templateName">template location</param>
/// <returns>The corresponding template name or null</returns>
public override string GetTemplateNameFromLocation(string location)
{
//return Path.ChangeExtension(location, string.Empty);
return Path.ChangeExtension(location, null);
}

#region FileSystemWatcher Events

private void OnChanged(object source, FileSystemEventArgs e)
{
string fullpath = e.FullPath.Replace('//', '/');
fileSet[fullpath] = locationRoot;
}

private void OnRenamed(object source, RenamedEventArgs e)
{
string fullpath = e.FullPath.Replace('//', '/');
fileSet[fullpath] = locationRoot;

fullpath = e.OldFullPath.Replace('//', '/');
fileSet[fullpath] = locationRoot;
}

#endregion
}

public class Link
{
public string faqid;
public string faqtitle;
}

public class User
{
public string Name = "";
public string Age = "";
}

public static class FileHelp
{
public static string Read(string filename,string Dir)
{

filename = AppDomain.CurrentDomain.BaseDirectory + Dir + filename;
using(FileStream fs = new FileStream(filename,FileMode.Open,FileAccess.Read))
{
StreamReader sr = new StreamReader(fs,Encoding.Default);
return sr.ReadToEnd();
}

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: