ASP.NET静态页生成方法(模板替换)

本文实例讲述了ASP.NET静态页生成方法的一种简单方法,就是替换内容法。

适用场景

模板比较固定,页面替换内容较少。

基本原理

此方法中静态页生成用到的就是匹配跟替换了,首先得读取模板页的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();
    }
}

总结一下

从代码可以看得出来,生成静态页面其实就是这么一个过程:读取模板页的源码->匹配替换自定义的标签为实际内容->最后再生成新的html文件,思路就这么走,以前没有动手过,觉得太复杂了,如今主动写的时候,发现也不算很复杂。
一个丑陋的示例图^^

注:页面中如果有需要及时显示的数据内容,可以用Ajax异步实时获取一下数据。

取出数据循环起来,批量生成你的静态页面吧。

posted @ 2015-11-23 17:55  Mr. Hu  阅读(590)  评论(0编辑  收藏  举报
Map