靜態(tài)頁生成用到最多的就是匹配跟替換了,首先得讀取模板頁的html內容,然后進行你自己定義的標簽匹配,比如說我要把我定義的標題標簽換成讀取數據庫的標題內容,那么可以直接讀取數據庫的標題,然后直接進行替換,然后生成html文件就OK了。
/// summary>
/// 解析模板的html中匹配的標簽,進行替換(暫時只能用于沒有分頁的頁面)
/// /summary>
/// param name="html">HTML/param>
/// returns>返回替換后的HTML/returns>
public static string ReturnHtml(string html)
{
string newhtml = html;
newhtml = newhtml.Replace("#Title#>", "這個是標題替換");//替換標題
//newhtml = newhtml.Replace("#Content#>", "這個是內容替換");//替換標題
newhtml = CreateList(newhtml);
return newhtml;
}
/// summary>
/// 讀取HTML文件
/// /summary>
/// param name="temp">html文件的相對路徑/param>
/// returns>返回html/returns>
public static string ReadHtmlFile(string temp)
{
StreamReader sr = null;
string str = "";
try
{
sr = new StreamReader(HttpContext.Current.Server.MapPath(temp), code);
str = sr.ReadToEnd(); // 讀取文件
}
catch (Exception exp)
{
HttpContext.Current.Response.Write(exp.Message);
HttpContext.Current.Response.End();
}
finally
{
sr.Dispose();
sr.Close();
}
return str;
}
/// summary>
/// 生成html文件
/// /summary>
/// param name="filmname">文件名(帶相對路徑路徑,如:../a.html)/param>
/// param name="html">html內容(整個)/param>
public static void writeHtml(string filmname, string html)
{
System.Text.Encoding code = System.Text.Encoding.GetEncoding("utf-8");
string htmlfilename = HttpContext.Current.Server.MapPath(filmname);
string str = html;
StreamWriter sw = null;
// 寫文件
try
{
sw = new StreamWriter(htmlfilename, false, code);
sw.Write(str);
sw.Flush();
}
catch (Exception ex)
{
HttpContext.Current.Response.Write(ex.Message);
HttpContext.Current.Response.End();
}
finally
{
sw.Close();
}
}
從代碼可以看得出來,生成靜態(tài)頁面其實就是這么一個過程:讀取模板頁的源碼->匹配替換自定義的標簽為實際內容->最后再生成新的html文件,思路就這么走,以前沒有動手過,覺得太復雜了,如今主動寫的時候,發(fā)現也不算很復雜。
最后,如果說有些生成分頁列表的,也就是把列表頁面進行循環(huán)生成,有多少頁就生成多少個靜態(tài)頁文件,如果有不懂的可以回復問,我懂的我盡量為大家解答,當然,不懂的我也無能為力了,畢竟我也是剛接觸這功能,現在暫時弄得一個最簡陋的樣子,附圖上來給大家笑話笑話: