asp .net 模板引擎 使用 Razor 生成html靜態頁面
剛開始不是理解 寫完之後 覺得還蠻簡單的
分為這幾個步驟
1.獲取頁面模板Html
2.獲取數據
3.解析模板和數據,生成靜態頁Html代碼
4.生成靜態文件
模板形式是mvc的模式,會mvc 看一下就懂了
主要是第2步和第3步
需要應用下面文件
RazorEngine.dll
System.Web.Razor.dll
/// <summary>
/// 獲取頁面的Html代碼
/// </summary>
/// <param name="url">模板頁面路徑</param>
/// <param name="encoding">頁面編碼</param>
/// <returns></returns>
public string GetHtml(string url, System.Text.Encoding encoding)
{
byte[] buf = new WebClient().DownloadData(url);
if (encoding != null) return encoding.GetString(buf);
string html = System.Text.Encoding.UTF8.GetString(buf);
encoding = GetEncoding(html);
if (encoding == null || encoding == System.Text.Encoding.UTF8) return html;
return encoding.GetString(buf);
}
/// <summary>
/// 獲取頁面的編碼
/// </summary>
/// <param name="html">Html源碼</param>
/// <returns></returns>
public System.Text.Encoding GetEncoding(string html)
{
string pattern = @"(?i)\bcharset=(?<charset>[-a-zA-Z_0-9]+)";
string charset = Regex.Match(html, pattern).Groups["charset"].Value;
try { return System.Text.Encoding.GetEncoding(charset); }
catch (ArgumentException) { return null; }
}
/// <summary>
/// 創建靜態文件
/// </summary>
/// <param name="result">Html代碼</param>
/// <param name="createpath">生成路徑</param>
/// <returns></returns>
public bool CreateFileHtmlByTemp(string result, string createpath)
{
if (!string.IsNullOrEmpty(result))
{
//if (string.IsNullOrEmpty(createpath))
//{
// createpath = "/default.html";
//}
//string filepath = createpath.Substring(createpath.LastIndexOf(@"\"));
//createpath = createpath.Substring(0, createpath.LastIndexOf(@"\"));
//if (!Directory.Exists(createpath))
//{
// Directory.CreateDirectory(createpath);
//}
//createpath = createpath + filepath;
try
{
FileStream fs2 = new FileStream(createpath, FileMode.Create);
StreamWriter sw = new StreamWriter(fs2, new System.Text.UTF8Encoding(false));//去除UTF-8 BOM
sw.Write(result);
sw.Close();
fs2.Close();
fs2.Dispose();
return true;
}
catch { return false; }
}
return false;
}
主要部分
1.數據
var GetJosn = new DataName() { Name = "這裏是文章標題", ThemeName = "<span style=\"color:red;\">這裏是文章內容</span>" };
var Entity = new DataName();//實體
這一部分要註意的是實體類
反射部分
Type typeT = GetJosn.GetType();
Type typeEn = Entity.GetType();
System.Reflection.PropertyInfo[] propertyinfosT = typeT.GetProperties();
foreach (System.Reflection.PropertyInfo propertyinfoT in propertyinfosT)
{
System.Reflection.PropertyInfo propertyinfoEn = typeEn.GetProperty(propertyinfoT.Name);
if (propertyinfoEn != null && propertyinfoT.GetValue(GetJosn, null) != null)
{
propertyinfoEn.SetValue(Entity, propertyinfoT.GetValue(GetJosn, null), null);
}
}
html 頁面是代碼
<body style="color:aqua;font-size:30px;">
@Model.Name
@Model.ThemeName
</body>
//解析模板生成靜態頁Html代碼
result = Razor.Parse(“模板hmtl”, Entity);//Entity屍體數據
看得懂 主要部分基本就可以了
asp .net 模板引擎 使用 Razor 生成html靜態頁面