由于業(yè)務(wù)需要,得把頁(yè)面按照模板頁(yè)生成靜態(tài)頁(yè)面,所以自己就琢磨了下,寫些思路,以備日后需要的時(shí)候用。
靜態(tài)頁(yè)生成用到最多的就是匹配跟替換了,首先得讀取模板頁(yè)的html內(nèi)容,然后進(jìn)行你自己定義的標(biāo)簽匹配,比如說我要把我定義的標(biāo)題標(biāo)簽換成讀取數(shù)據(jù)庫(kù)的標(biāo)題內(nèi)容,那么可以直接讀取數(shù)據(jù)庫(kù)的標(biāo)題,然后直接進(jìn)行替換,然后生成html文件就OK了。
代碼:
/// <summary> /// 解析模板的html中匹配的標(biāo)簽,進(jìn)行替換(暫時(shí)只能用于沒有分頁(yè)的頁(yè)面) /// </summary> /// <param name="html">HTML</param> /// <returns>返回替換后的HTML</returns> public static string ReturnHtml(string html) { string newhtml = html; newhtml = newhtml.Replace("<#Title#>", "這個(gè)是標(biāo)題替換");//替換標(biāo)題 //newhtml = newhtml.Replace("<#Content#>", "這個(gè)是內(nèi)容替換");//替換標(biāo)題 newhtml = CreateList(newhtml); return newhtml; }
/// <summary> /// 讀取HTML文件 /// </summary> /// <param name="temp">html文件的相對(duì)路徑</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">文件名(帶相對(duì)路徑路徑,如:../a.html)</param> /// <param name="html">html內(nèi)容(整個(gè))</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)頁(yè)面其實(shí)就是這么一個(gè)過程:讀取模板頁(yè)的源碼->匹配替換自定義的標(biāo)簽為實(shí)際內(nèi)容->最后再生成新的html文件,思路就這么走,以前沒有動(dòng)手過,覺得太復(fù)雜了,如今主動(dòng)寫的時(shí)候,發(fā)現(xiàn)也不算很復(fù)雜。
最后,如果說有些生成分頁(yè)列表的,也就是把列表頁(yè)面進(jìn)行循環(huán)生成,有多少頁(yè)就生成多少個(gè)靜態(tài)頁(yè)文件,如果有不懂的可以回復(fù)問,我懂的我盡量為大家解答,當(dāng)然,不懂的我也無能為力了,畢竟我也是剛接觸這功能,現(xiàn)在暫時(shí)弄得一個(gè)最簡(jiǎn)陋的樣子,附圖上來給大家笑話笑話:

最后是求助環(huán)節(jié):這是小子的小站:www.weixh.net,求助SEO的大嬸,請(qǐng)問我該怎么推廣呢?
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注