自己写的模板引擎,模板生成静态页面

自己写的模板引擎,模板生成静态页面,第1张

概述开发网站需要用到模板引擎,自己写了一个。支持foreach嵌套,支持if else嵌套,支持foreach和if else混合嵌套,支持include,支持set,支持cutstr和html2text

    开发网站需要用到模板引擎,自己写了一个。支持foreach嵌套,支持if else嵌套,支持foreach和if else混合嵌套,支持include,支持set,支持cutstr和HTML2text函数。

HTML模板示例代码如下:

index.HTML页面:

<!DOCTYPE HTML><HTMLhead>    Meta http-equiv="Content-Type" content="text/HTML; charset=utf-8" />    content="wIDth=device-wIDth,minimum-scale=1,initial-scale=1,maximum-scale=1,user-scalable=1;" ID="vIEwport" name="vIEwport" ="X-UA-Compatible"="IE=edge,Chrome=1" name="keywords"="${site.keywords}" ="description"="${site.description}" link href="theme/CSS/Int.CSS" rel="stylesheet" ="theme/CSS/head.CSS"="theme/CSS/index.CSS"="theme/CSS/lrtk.CSS"="theme/CSS/more.CSS"script type="text/JavaScript" src="theme/Js/jquery-1.11.3.Js"></script="theme/Js/layout.Js"="theme/Js/more.Js"src="theme/Js/jquery.superslIDe.2.1.1.Js" type="text/JavaScript"Title>首页-${site.sitename}</>            body<!--头部开始-->    div class="header">        ="w">            ="fl logo">                a ="/">                    img ="${site.logoUrl}"adiv="sj_language"#if ${site.ID}=="1"="/en/index.HTML"><em ="china" style="background: url(theme/images/eng.jpg) left center no-repeat;">Englishemi style="background: url(theme/images/china.jpg) left center no-repeat;">中文版i#else="/cn/index.HTML"="china"#end if主菜单-->            #include ="/templates/${site.folder}/rootmenu.HTML" />            ="language"span span="clear"子菜单-->        ="/templates/${site.folder}/submenu.HTML" />        头部结束="SimpoAll" 新的轮播图开始 >                var scrollimg;            ="mrBox"="next" onclick="scrollimg.next()"="imgBox"ul>                        #foreach List="banners" model="ban" where="siteID=1" li="${ban.linkUrl}" target="_blank">                            ="${ban.imgurl}" /></#/foreach="prve"="scrollimg.prev()"="theme/Js/slIDer-H5.Js">                (function () {                    $(window).resize( () {                         ul = $('.imgBox).clone().HTML();                        $().HTML("");                         ID  (new Date()).getTime();                        $(ul).attr(ID,ID).appendTo($());                         height body).height();                         wIDth ).wIDth();                         newwIDth ).wIDth();                        $().CSS(wIDth.imgBox ul li.imgBox ul li img/*                            注意:$.mggScrollimg返回的scrollimg对象上有                                    next,prev,go三个方法,可以实现外部对滚动索引的控制。                            如:scrollimg.next();//会切换到下一张图片                                scrollimg.go(0);//会切换到第一张图片                        */                        scrollimg  $.mggScrollimg(#' + ID,{                            loop: true//循环切换                            auto: 自动切换                            auto_wait_time: 3000轮播间隔                            scroll_time: 300滚动时长                            callback:  (ind) {这里传过来的是索引值                                $(#page).text(ind + 1);                            }                        });                    });                    $(window).resize();                })()            >             新的轮播图结束 -->            关于我们开始="about_bg"="about"#set data="channel"="gywm"="Title='关于我们'" />                    ="qyjj"="Title='企业简介'" h1 ="biaot"="/${site.folder}/List${qyjj.ID}.HTML">${gywm.Title}h1="subMenu"="parent.Title='关于我们'"  dldt="/${site.folder}/List${subMenu.ID}.HTML"="${subMenu.iconUrl}" dd>${subMenu.Title}关于我们结束-->            业务单元开始="ywdy"="Title='业务单元'" ="Business_bg"="#"="Business">${ywdy.Title}="yw_pic"="theme/images/yw.png" />                        业务单元结束投资者关系开始="investor_bg"="investor"="tzzgx"="Title='投资者关系'" ="cwbg"="Title='财务报告'" ="/${site.folder}/List${cwbg.ID}.HTML">投资者关系="content"="con"="channel.Title='投资者关系'" page="1" pageSize="1"  p>${cutstr(${con.contents},315)}...="/${site.folder}/content${con.ID}.HTML">【详情】="parent.Title='投资者关系'"  投资者关系结束新闻综合类开始="information">                新闻资讯开始-->                ="news"="xwzx"="Title='新闻中心'" ="mtjj"="Title='媒体聚焦'" ="/${site.folder}/List${mtjj.ID}.HTML">${xwzx.Title}="current news1"="news2"="newBox1"="channel.Title='媒体聚焦'"="3"  >                                ="${con.imgurl}" h2>${con.Title}label>${con.publishTime}>                    ="newBox2"="display: none"="channel.Title='最新公告'">                新闻资讯结束-->                社会责任开始="responsibility"="shzr"="Title='社会责任'" ="/${site.folder}/List${shzr.ID}.HTML">${shzr.Title}="zeren"="border"="zr_List"="channel.Title='社会责任'"="5"  ${con.curPageSort}==1>                                    button ="btn_on btn"="button"button="btn">                                    ="neir">                                        >                        社会责任结束新闻综合类结束总裁寄语开始="PresIDent_bg"="PresIDent"="zcjy"="Title='总裁寄语'" >${zcjy.Title}="Message_Box"="Message"="channel.Title='总裁寄语'">                             ="j${con.curPageSort}">                                 ="j${con.curPageSort}"="display: none;">                                                           ${con.contents}                             ="qh"="y1 qh_on"="y2"="y3"总裁寄语结束合作伙伴开始="Partner_bg"="Partner"h3>合作伙伴="links"="lk"="type=2 and siteID=1" ="${lk.linkUrl}">${lk.Title}合作伙伴结束-->                底部开始="cai_bg"="Web_Icon"底部结束="copyright_bottom"                    ${site.copyright}br />                    备案号:${site.siteRecord}                                    ${site.statScript}                >
VIEw Code

rootmenu.HTML页面:

="pad-nav"="rootMenu"="channel.siteID=${site.ID} and channel.level=1"  ${rootMenu.sort}${channel.ID}==0="index.HTML" class="cpselect"="showPhonesubMenu('${rootMenu.Title}')">${rootMenu.Title}${rootMenu.ListType}=="5"${rootMenu.ID}=="${parentChannel.ID}"="#"="/${site.folder}/List${rootMenu.ID}.HTML"="two_nav" phone-menu-Title="${rootMenu.Title}"="parent.Title='${rootMenu.Title}'"  ="fl nav"="cur"="smen">             ="cur"="showSubMenu('${rootMenu.Title}')"="smen"${parentChannel.ID}=="${channel.ID}">
VIEw Code

List.HTML页面:

="theme/Js/jquery-1.9.1.Js"<script src="Js/jquery.superslIDe.2.1.1.Js" type="text/JavaScript"></script> PC端轮播图Js >${channel.Title}-${parentChannel.Title}-${site.sitename}        $(document).ready( () {             topMain ".nav_part).height()对象的的高度             nav );            $(window).scroll( () {                if ($(window).scrolltop()  topMain) {如果滚动条顶部的距离大于topMain则就nav导航就添加类.nav_scroll,否则就移除。                    nav.addClass(nav_scroll);                }                else {                    nav.removeClass();                }            });        })    ="index.HTML"="theme/images/logo.png"/>        广告图开始="gg_pic"="theme/images/ejbg.jpg" 广告图结束内容区域开始="Main_part"左侧导航开始="/templates/${site.folder}/leftmenu.HTML" 左侧导航结束右侧内容开始="nr_part"="position"="fl">${channel.Title}="fr">当前位置:${parentChannel.ID}!=0>${parentChannel.Title}>="Media_Focus"="jujiao"delalt=""="${channel.iconUrl}"                         ${channel.Title}main="true" List channel="${channel.ID}"="${pager.page}"="10"  >[${channel.Title}]="pag"${pager.prePage}="List${channel.ID}.HTML"="">上一页="List${channel.ID}-${pager.prePage}.HTML"="margin-right: 40px; Font-size: 12px; color: #666;">${pager.page} / ${pager.pageCount}${pager.nextPage}="List${channel.ID}.HTML">下一页="List${channel.ID}-${pager.nextPage}.HTML"右侧内容结束-->        内容结束-->        合作伙伴结束--<!--底部开始<iframe src="footer.HTML" wIDth="100%" height="365" frameborder="0" scrolling="no"></iframe>            ${site.copyright}            备案号:${site.siteRecord}                    ${site.statScript}        >
VIEw Code

 

模板引擎代码如下:

Tag类:

using System; System.Collections.Generic; System.linq; System.Text;namespace DAL.Parser{    /// <summary>    /// 标签    </summary>    public  Tag    {        <summary>         标签开始位置        </summary>        int start { get; set; }         标签标记        public Token token {  标签字符串        string Tagstr {  标签字符串长度        int length        {            get            {                return Tagstr.Length;            }        }         标签结束位置         end        {            return start + length;            }        }         标签        </summary>        <param name="start">标签开始位置</param>        <param name="token">标签标记<param name="Tagstr">标签字符串</param>        public Tag(int start,Token token,string Tagstr)        {            this.start = start;            this.token = token;            this.Tagstr = Tagstr;        }    }}
VIEw Code

Token类:

 标签标记    enum Token    {         标签开始        </summary>        Tagstart, 标签结束                TagEnd,1)"> else标签                ElseTag    }}
VIEw Code

IfTag类:

 System.Text; System.Text.RegularExpressions; if标签     IfTag    {         开始标签        public Tag startIf {  else标签,可为null        public Tag elseTag {  结束标签        public Tag endIf { ; }         页面HTML        string pageHTML {  if分支HTML         ifHTML        {            if (elseTag != null)                {                    return pageHTML.Substring(startIf.start + startIf.length,elseTag.start - startIf.start - startIf.length);                }                else                {                     startIf.length);                }            }        }         else分支HTML         elseHTML        {            null && elseTag.start + elseTag.length < endIf.start)                {                    return pageHTML.Substring(elseTag.start + elseTag.length,endIf.start - elseTag.start - elseTag.length);                }                return .Empty;                }            }        }         结果HTML        string resultHTML {  if标签        <param name="startIf">开始标签<param name="elseTag">else标签<param name="endIf">结束标签<param name="pageHTML">页面HTMLpublic IfTag(Tag startIf,Tag elseTag,Tag endIf,1)"> pageHTML)        {            this.startIf = startIf;            this.endIf = endIf;            this.elseTag = elseTag;            this.pageHTML = pageHTML;            this.resultHTML = .Empty;            if (!Regex.IsMatch(startIf.Tagstr,@"${([^${}]+)\.([^${}]+)}")) //如果没有未解析的Model            {                bool compareOr = false;                foreach (string strOr in startIf.Tagstr.Replace("<#if",1)">"").Replace(>"").Split(new string[] {  or " },StringSplitoptions.RemoveEmptyEntrIEs)) 遍历or分隔                {                    bool compareAnd = true;                    string strAnd in strOr.Split( and 遍历and分隔                    {                        Regex reg = new Regex(([^\s]*)[\s]*(==|!=|大于|小于)[\s]*([^\s]*)" reg.Matches(strAnd);                        foreach (Match match in mc)                        {                            #region 比较                            switch (match.Groups[2].Value)                            {                                case ==:                                    if (match.Groups[1].Value.Replace(\""") != match.Groups[3].Value.Replace(""))                                    {                                        compareAnd = ;                                    }                                    break;                                !="") == match.Groups[大于 d;                                    if (int.TryParse(match.Groups[1].Value,1)">out d) && 3].Value,1)">out d))                                    {                                        if (Convert.ToInt32(match.Groups["")) <= Convert.ToInt32(match.Groups[)))                                        {                                            compareAnd = ;                                        }                                    }                                    小于"")) >= Convert.ToInt32(match.Groups[default;                            }                            #endregion                        }                    }  end 遍历and分隔                     (compareAnd)                    {                        compareOr = ;                    }                } 遍历or分隔                 (compareOr)                {                    resultHTML = ifHTML;                    ;                }                resultHTML = elseHTML;            }        } end 构造函数    } end IfTag 类} end namespace
VIEw Code

ForeachTag类:

 System.Text.RegularExpressions; Models; Foreach标签     ForeachTag    {        public Tag startForeach { public Tag endForeach {  标签内HTML         INNERHTML        {            return pageHTML.Substring(startForeach.start + startForeach.length,endForeach.start - startForeach.start - startForeach.length);            }        }         列表的标识        string List {  列表的model        string model {  where        string where {  当面页数        int page {  每页数据条数        int pageSize {  该foreach是否是当前页面的主列表        bool main = ;         栏目名称或栏目ID        string channel {  Foreach标签        <param name="startForeach"><param name="endForeach">public ForeachTag(Tag startForeach,Tag endForeach,1)">this.startForeach = startForeach;            this.endForeach = endForeach;             pageHTML;            Regex reg = ([^\s]+)\s*=\s*""([^""]+)"" reg.Matches(startForeach.Tagstr);            foreach (Match m  mc)            {                switch (m.Groups[1].Value)                {                    List:                        this.List = m.Groups[].Value;                        modelthis.model = m.Groups[wherethis.where = m.Groups[pageif (Regex.IsMatch(m.Groups[2].Value,1)">^\d+$))                        {                            this.page = Convert.ToInt32(m.Groups[].Value);                        }                        pageSizethis.pageSize = Convert.ToInt32(m.Groups[channelthis.channel = m.Groups[mainthis.main = ;                        ;                }            }        }  end 构造函数 end ForeachTag 类}  end namespace
VIEw Code

PageNum类:

 分页数字类     PageNum    {         分页数字        int num {  是否非数字,1:非数字,0数字,用来显示省略号        int nan { <param name="num">分页数字<param name="nan">是否非数字,1:非数字,0数字,用来显示省略号public PageNum(int num,1)">int nan = 0)        {            this.num = num;            this.nan = nan;        }    }}
VIEw Code

 

模板引擎TemplateDal类:

 System.IO; System.Reflection; System.Web; DAL.Parser; DAL{     模板引擎     TemplateDal    {        #region 变量         分页数字列表        static List<PageNum> pageNumList = ;        #endregion        #region 载入模板         载入模板        static string LoadTemplate(httpServerUtilityBase server,1)"> url)        {            string result = .Empty;            StreamReader sr = new StreamReader(server.MapPath(url),EnCoding.UTF8);            result = sr.ReadToEnd();            sr.Close();             result;        }        #region 写入模板         写入模板        voID WriteTemplate(httpServerUtilityBase server,1)">string url,1)"> HTML)        {            .Empty;            string path = server.MapPath(url);            if (!Directory.Exists(Path.GetDirectoryname(path)))            {                Directory.CreateDirectory(Path.GetDirectoryname(path));            }            fileStream fs =  fileStream(path,fileMode.Create,fileAccess.Write);            StreamWriter sw =  StreamWriter(fs,EnCoding.UTF8);            sw.Write(HTML);            sw.Close();            fs.Close();        }        #region 替换页面model         替换页面model        string ReplaceModels(string pageHTML,Dictionary<string,1)">object> data)        {            Regex reg =  reg.Matches(pageHTML);            if (data.Keys.Contains<string>(m.Groups[].Value))                {                    object model = data[m.Groups[].Value];                    Type type = model.GetType();                    PropertyInfo propertyInfo = type.GetProperty(m.Groups[].Value);                    object obj = propertyInfo.GetValue(model,1)">);                    string val = .Empty;                    if (obj != )                    {                        if (obj.GetType() == typeof(DateTime))                        {                            val = ((DateTime)obj).ToString(yyyy-MM-dd);                        }                                                {                            val = obj.ToString();                        }                    }                    pageHTML = pageHTML.Replace(${" + m.Groups[1].Value + .2].Value + } pageHTML;        }        #region 替换列表的model         替换列表的model        string HTML,1)">string model,1)">object${[^${}]+\.([^${}]+)} reg.Matches(HTML);             mc)            {                Type type = data.GetType();                PropertyInfo propertyInfo = type.GetProperty(m.Groups[].Value);                object obj = propertyInfo.GetValue(data,1)">);                .Empty;                (DateTime))                    {                        val = ((DateTime)obj).ToString();                    }                                        {                        val = obj.ToString();                    }                }                HTML = HTML.Replace(" + model +  HTML;        }        #region 判断页面是否存在 foreach 标签         判断页面是否存在 foreach 标签        bool HasForeach( HTML)        {            Regex reg = <!--[\s]{0,1}#[\s]{0,1}foreach[\s]+[^<>${}]*--> RegexOptions.Singleline);             reg.IsMatch(HTML);        }        #region 替换foreach         替换foreach        string ReplaceLists( data)        {            #region 生成标签集合            Regex regStartForeach =  RegexOptions.Singleline);            Regex regEndForeach =  RegexOptions.Singleline);            MatchCollection mcStartForeach = regStartForeach.Matches(pageHTML);            MatchCollection mcEndForeach = regEndForeach.Matches(pageHTML);            List<Tag> tagList = new List<Tag>();            foreach (Match mStartForeach  mcStartForeach)            {                Tag tag =  Tag(mStartForeach.Index,Token.Tagstart,mStartForeach.Value);                tagList.Add(tag);            }            foreach (Match mEndForeach  mcEndForeach)            {                Tag tag =  Tag(mEndForeach.Index,Token.TagEnd,mEndForeach.Value);                tagList.Add(tag);            }            tagList.sort((a,b) => a.start - b.start);            #endregion            for (int i = 0; i < tagList.Count; i++) 遍历标签集合            {                Tag tag = tagList[i];                int depth = if (tag.token == Token.Tagstart)                {                    int j = i + 1; j < tagList.Count; j++if (tagList[j].token == Token.TagEnd && depth == )                        {                            string resultHTML = .Empty;                            ForeachTag foreachTag =  ForeachTag(tag,tagList[j],pageHTML);                            #region 替换                            switch (foreachTag.List)                            {                                :                                    StringBuilder sb =  StringBuilder();                                    ChannelDal m_ChannelDal =  ChannelDal();                                    List<CMS_channel_ext> channelList = m_ChannelDal.GetList(foreachTag.where);                                    foreach (CMS_channel_ext channel  channelList)                                    {                                        sb.Append(TemplateDal.ReplaceModels(foreachTag.INNERHTML,foreachTag.model,channel));                                    }                                    resultHTML = foreachTag.pageHTML.Substring(0,foreachTag.startForeach.start) + sb.ToString() + foreachTag.pageHTML.Substring(foreachTag.endForeach.start + foreachTag.endForeach.length);                                    content:                                    sb =  StringBuilder();                                    ContentDal m_ContentDal =  ContentDal();                                    PagerModel pager =  PagerModel();                                    pager.rows = foreachTag.pageSize;                                    pager.page = foreachTag.page;                                    List<CMS_content_ext> contentList = m_ContentDal.GetList(ref pager,foreachTag.channel,foreachTag.foreach (CMS_content_ext content  contentList)                                    {                                        sb.Append(TemplateDal.ReplaceModels(foreachTag.INNERHTML,content));                                    }                                    resultHTML = foreachTag.pageHTML.Substring(links StringBuilder();                                    linksDal m_linksDal =  linksDal();                                    List<CMS_links_ext> linksList = m_linksDal.GetList(foreachTag.foreach (CMS_links_ext links  linksList)                                    {                                        sb.Append(TemplateDal.ReplaceModels(foreachTag.INNERHTML,links));                                    }                                    resultHTML = foreachTag.pageHTML.Substring(banners StringBuilder();                                    BannersDal m_BannersDal =  BannersDal();                                    List<CMS_banners_ext> bannersList = m_BannersDal.GetList(foreachTag.foreach (CMS_banners_ext banners  bannersList)                                    {                                        sb.Append(TemplateDal.ReplaceModels(foreachTag.INNERHTML,banners));                                    }                                    resultHTML = foreachTag.pageHTML.Substring(pages (data.ContainsKey(foreachTag.List))                                    {                                        sb =  StringBuilder();                                        List<PageNum> pageNumList = data[foreachTag.List] as List<PageNum>;                                        foreach (PageNum pageNum  pageNumList)                                        {                                            sb.Append(TemplateDal.ReplaceModels(foreachTag.INNERHTML,pageNum));                                        }                                        resultHTML = foreachTag.pageHTML.Substring( foreachTag.endForeach.length);                                    }                                    :                                    resultHTML = foreachTag.pageHTML.Substring(#endregion                             resultHTML;                        }                        if (tagList[j].token == Token.Tagstart)                        {                            depth++;                        }                         Token.TagEnd)                        {                            depth--;                        }                    }                }            }            #region 判断页面是否存在 if else 标签         判断页面是否存在 if else 标签        bool HasIfElse(#region 替换 if else end if         替换 if else end if        string ReplaceIfElse(            Regex regStartIf =  RegexOptions.Singleline);            Regex regElseTag =  RegexOptions.Singleline);            Regex regEndIf =  RegexOptions.Singleline);            MatchCollection mcStartIf = regStartIf.Matches(pageHTML);            MatchCollection mcElseTag = regElseTag.Matches(pageHTML);            MatchCollection mcEndIf = regEndIf.Matches(pageHTML);            List<Tag> tagList = foreach (Match mStartIf  mcStartIf)            {                Tag tag =  Tag(mStartIf.Index,mStartIf.Value);                tagList.Add(tag);            }            foreach (Match mEndIf  mcEndIf)            {                Tag tag =  Tag(mEndIf.Index,mEndIf.Value);                tagList.Add(tag);            }            foreach (Match mElseTag  mcElseTag)            {                Tag tag =  Tag(mElseTag.Index,Token.ElseTag,mElseTag.Value);                tagList.Add(tag);            }            tagList.sort((a,1)">            {                Tag TagstartIf = tagList[i];                Tag tagElseTag = if (TagstartIf.token == Token.Tagstart) 是if标签1; j < tagList.Count; j++) 遍历if标签后面的标签                    {                        if (depth == if (tagList[j].token == Token.ElseTag) 是else标签                            {                                tagElseTag = tagList[j];                            }                             Token.TagEnd)                            {                                IfTag ifTag =  IfTag(TagstartIf,tagElseTag,pageHTML);                                if (!Regex.IsMatch(ifTag.startIf.Tagstr,1)">                                {                                    return pageHTML.Substring( ifTag.endIf.length);                                }                            }                        }                        ;                        }                    }                }            }            #region 替换页面function         替换页面function        string ReplaceFunctions(#region 替换cutstr函数            Regex reg = ${cutstr\((.*),([\d]+)\)} mc)            {                Regex reg2 = (?:<[^<>]+[\s]+[^<>]+[\s]*/>)|(?:<[^<>]+[\s]+[^<>]+[\s]*>)|(?:</[^<>]+>)|(?:&nbsp;)string HTML = reg2.Replace(m.Groups[if (HTML.Length > Convert.ToInt32(m.Groups[].Value))                {                    pageHTML = pageHTML.Replace(m.Value,HTML.Substring(].Value)));                }                                {                    pageHTML = pageHTML.Replace(m.Value,HTML);                }            }            #region 替换HTML2text函数            reg = ${HTML2text\((.+),RegexOptions.IgnoreCase);            mc =);                pageHTML =#region 替换replace函数${replace\(([^\(\),]+),([^\(\),]+)\)} mc)            {                pageHTML = pageHTML.Replace(m.Value,m.Groups[1].Value.Replace(m.Groups[2].Value.Replace('""),1)">)));            }            #region 替换页面include         替换页面include        string ReplaceIncludes(httpServerUtilityBase server,1)"> pageHTML)        {            Regex reg =  mc)            {                StreamReader sr = new StreamReader(server.MapPath(m.Groups[].Value),EnCoding.UTF8);                string HTML = sr.ReadToEnd();                sr.Close();                pageHTML =#region 替换页面set         替换页面set        string ReplaceSets( mc)            {                Regex regSub = string data = string model = where = foreach (Match mSub  mcSub)                {                    switch (mSub.Groups[].Value)                    {                        data:                            data = mSub.Groups[].Value;                            :                            model = mSub.Groups[:                            where = mSub.Groups[;                    }                }                 (data)                {                    :                        ChannelDal m_ChannelDal =  ChannelDal();                        CMS_channel channel = m_ChannelDal.Get();                        Dictionary<object> dic = new Dictionary<();                        dic.Add(model,channel);                        pageHTML = pageHTML.Replace(m.Value,1)">);                        pageHTML = TemplateDal.ReplaceModels(pageHTML,dic);                        ;                }            }            #region 获取head内容         获取head内容        string GetheadHTML(<head>([\S\s]*)</head> reg.Match(pageHTML);            return m.Groups[].Value;        }        #region 获取body内容         获取body内容        string GetbodyHTML(<body>([\S\s]*)</body>#region 获取一个ForeachTag         获取一个ForeachTag        static ForeachTag GetForeachTag(string List = )                        {                            ForeachTag foreachTag = if (foreachTag.main && foreachTag.List == List)                            {                                 foreachTag;                            }                        }                        ;                        }                    }                }            } end 遍历标签集合             ;        }            } end of class TemplateDalend of namespace DAL
VIEw Code

 

使用模板引擎生成静态页面:

 System.Threading; System.Web.Mvc; System.Web.Script.Serialization; Common; Common.Utils; DAL; DBHelper; NetCMS.Web.Areas.admin.Controllers{     前台更新     FrontPageManageController : Common.ControllerBase    {        #region 变量        private SiteDal m_SiteDal =  SiteDal();        private ChannelDal m_ChannelDal =  ChannelDal();        private ContentDal m_ContentDal =  ContentDal();         进度总数        private double total =  当前进度        int cur =  错误信息        string errMsg = .Empty;        #region 替换         替换        string Replace(string templateHTML,1)"> dic)        {            templateHTML = TemplateDal.ReplaceSets(templateHTML);            templateHTML = TemplateDal.ReplaceModels(templateHTML,dic);            templateHTML = TemplateDal.ReplaceIncludes(Server,templateHTML);            templateHTML =while (TemplateDal.HasIfElse(templateHTML))            {                templateHTML = TemplateDal.ReplaceIfElse(templateHTML);            }             (TemplateDal.HasForeach(templateHTML))            {                templateHTML = TemplateDal.ReplaceLists(templateHTML,dic);            }             TemplateDal.ReplaceIfElse(templateHTML);            }            templateHTML = TemplateDal.ReplaceFunctions(templateHTML);            string headHTML = TemplateDal.GetheadHTML(templateHTML);            string bodyHTML = TemplateDal.GetbodyHTML(templateHTML);            StringBuilder sb =  StringBuilder();            sb.AppendFormat(<!DOCTYPE HTML>\r\n<HTML>\r\n<head>\r\n{0}\r\n</head>\r\n<body>\r\n{1}\r\n</body>\r\n</HTML>\r\n sb.ToString();        }        #region Index页面        [Permission(Code = Index)]        public ActionResult Index()        {             VIEw();        }        #region Update更新        [httpPost]        [Permission(Code =  ActionResult Update()        {            trynew Thread(new ThreadStart(delegate()                {                                        {                        Updatetheme();                        UpdateIndex();                        UpdateError();                        UpdateComments();                    }                    catch (Exception ex)                    {                        errMsg += ex.Message + <br />" + ex.StackTrace.Replace(\n);                    }                })).Start();                                    {                        UpdateList();                    }                                        {                        UpdateContent();                    }                    );                    }                })).Start();                return Content(OK);            }             (Exception ex)            {                 Content(ex.Message);            }        }        #region 更新theme         更新theme        voID Updatetheme()        {            List<CMS_site_ext> siteList = m_SiteDal.GetListAll();            foreach (CMS_site_ext site in siteList) 遍历站点string fromPath = Server.MapPath(string.Format(/templates/{0}/theme/string topath = Server.MapPath(/{0}/theme/;        }         更新theme中的文件        voID copythemefiles(string fromPath,1)"> topath)        {            Directory.Exists(topath))            {                Directory.CreateDirectory(topath);            }            string filePath  Directory.Getfiles(fromPath))            {                System.IO.file.copy(filePath,topath + Path.Getfilename(filePath),1)">string dirPath  Directory.GetDirectorIEs(fromPath))            {                int pos = dirPath.LastIndexOf(\);                copythemefiles(dirPath,topath + dirPath.Substring(pos + 1) + );            }        }        #region 更新index页面         更新index页面         UpdateIndex()        {            List<CMS_site_ext> siteList =;            string templateHTML = TemplateDal.LoadTemplate(Server,1)">/templates/{0}/index.HTML();                dic.Add(siteparentParentChannel CMS_channel());                dic.Add(parentChannel CMS_channel());                TemplateDal.WriteTemplate(Server,/{0}/index.HTMLif (i++ == /theme//index.HTML#region 更新List页面         更新List页面         UpdateList()        {            List<CMS_site_ext> siteList =            {                List<CMS_channel_ext> channelList = m_ChannelDal.GetList(channel.siteID={0}in channelList) 遍历栏目string.IsNullOrWhiteSpace(errMsg)) break; 有错误则跳出                    #region 获取父栏目                    CMS_channel parentParentChannel;                    CMS_channel parentChannel;                    if (channel.parentID == -)                    {                        parentChannel =  CMS_channel();                        parentChannel.parentID = -;                    }                                        {                        parentChannel = m_ChannelDal.Get(channel.parentID);                    }                    if (parentChannel.parentID == -)                    {                        parentParentChannel =  CMS_channel();                        parentParentChannel.parentID = -                    {                        parentParentChannel = m_ChannelDal.Get(parentChannel.parentID);                    }                    #endregion                    if (channel.ListType == ()Enums.ChannelListType.文字列表                        || channel.ListType == ()Enums.ChannelListType.图片列表                        || channel.ListType == ()Enums.ChannelListType.父级栏目)                    {                        #region 取模板                        string templatefilename = string.IsNullOrWhiteSpace(channel.template) ? List.HTML : channel.template;                        /templates/{0}/List/{1}#endregion                        #region 设置分页参数                        ForeachTag foreachTag = TemplateDal.GetForeachTag(templateHTML);                        PagerModel pager =  PagerModel();                        if (foreachTag != )                        {                            pager.rows = foreachTag.pageSize;                        }                                                {                            pager.rows = 20;                        }                        pager.page = do                        {                            List<CMS_content_ext> contentList = m_ContentDal.GetList();                            Dictionary<();                            dic.Add(pager filePath;                            if (pager.page == )                            {                                filePath = /{0}/List{1}.HTML/{0}/List{1}{2}.HTML-" + pager.page.ToString());                            TemplateDal.WriteTemplate(Server,dic));                        } while (pager.page++ <= pager.pageCount); 遍历每页数据                    }                    )Enums.ChannelListType.单篇文章)                    {                        CMS_content content = m_ContentDal.GetByChannelID(channel.ID);                        if (content == )                        {                            StringBuilder sb =  StringBuilder();                            sb.Append(<!DOCTYPE HTML>\r\n<HTML>\r\n<head>\r\n);                            sb.AppendFormat(<script type=\"text/JavaScript\">window.location = \"error.HTML\";</script></head>\r\n<body>\r\n</body>\r\n</HTML>\r\n);                            string filePath =                         {                            StringBuilder sb = <script type=\"text/JavaScript\">window.location = \"/{0}/content{1}.HTML\";</script>)Enums.ChannelListType.页面链接)                    {                        string url = .Empty;                        if (channel.pageUrl == comments.HTML)                        {                            url = /{0}/{1}                        {                            url = channel.pageUrl;                        }                        StringBuilder sb =  StringBuilder();                        sb.Append();                        sb.AppendFormat(<script type=\"text/JavaScript\">window.location = \"{0}\";</script>);                        ;                }  end 遍历 channelList            } end 遍历 siteList        }        #region 更新单个List页面         更新单个List页面        public ActionResult UpdateListSingle( ID)        {                        {                CMS_channel channel = m_ChannelDal.Get(ID);                CMS_site site = m_SiteDal.Get(channel.siteID);                                CMS_channel parentParentChannel;                CMS_channel parentChannel;                )                {                    parentChannel =  CMS_channel();                    parentChannel.parentID = -;                }                                {                    parentChannel = m_ChannelDal.Get(channel.parentID);                }                )                {                    parentParentChannel =  CMS_channel();                    parentParentChannel.parentID = -                {                    parentParentChannel = m_ChannelDal.Get(parentChannel.parentID);                }                #endregion                )Enums.ChannelListType.文字列表                    || channel.ListType == ()Enums.ChannelListType.图片列表                    || channel.ListType == ()Enums.ChannelListType.父级栏目)                {                    #region 取模板                     : channel.template;                                        ForeachTag foreachTag = TemplateDal.GetForeachTag(templateHTML);                    PagerModel pager =  PagerModel();                    )                    {                        pager.rows = foreachTag.pageSize;                    }                                        {                        pager.rows = ;                    }                    pager.page =                     {                        List<CMS_content_ext> contentList = m_ContentDal.GetList();                        Dictionary<();                        dic.Add( filePath;                        )                        {                            filePath =  pager.page.ToString());                        TemplateDal.WriteTemplate(Server,dic));                    }                 }                )Enums.ChannelListType.单篇文章)                {                    CMS_content content = m_ContentDal.GetByChannelID(channel.ID);                    )                    {                        StringBuilder sb =                     {                        StringBuilder sb = )Enums.ChannelListType.页面链接)                {                    )                    {                        url =                     {                        url = channel.pageUrl;                    }                    StringBuilder sb =  StringBuilder();                    sb.Append();                    sb.AppendFormat(var Json =                 {                    ok =  Json(Json);            }                            {                    ok = ex.Message                };                 Json(Json);            }        }        #region 更新content页面         更新content页面         UpdateContent()        {            List<CMS_content_ext> contentListAll = m_ContentDal.GetListAll();            in contentListAll) 遍历内容详情有错误则跳出                #region 获取下一篇、上一篇、栏目、站点、父栏目等                CMS_content_ext nextContent = m_ContentDal.GetNext(content.ID);                if (nextContent == )                {                    nextContent =  CMS_content_ext();                    nextContent.isNull = ;                }                CMS_content_ext preContent = m_ContentDal.GetPre(content.ID);                if (preContent == )                {                    preContent =  CMS_content_ext();                    preContent.isNull = ;                }                CMS_channel channel = m_ChannelDal.Get(content.channelID);                CMS_site site = m_SiteDal.Get(channel.siteID);                CMS_channel parentParentChannel;                CMS_channel parentChannel;                if (content.isPageUrl == /{0}/content{1}.HTML);                    TemplateDal.WriteTemplate(Server,sb.ToString());                }                string.IsNullOrWhiteSpace(content.template) ? content.HTML : content.template;                    /templates/{0}/content/{1}                    Dictionary<();                    dic.Add(preContentnextContent++;            }        }        #region 更新单个content页面         更新单个content页面        public ActionResult UpdateContentSingle(            {                CMS_content content = m_ContentDal.Get(ID);                #region 更新error页面         更新error页面         UpdateError()        {            List<CMS_site_ext> siteList =/templates/{0}/error.HTMLnew CMS_channel() { ID = -999 });                TemplateDal.WriteTemplate(Server,1)">/{0}/error.HTML#region 更新comments页面         更新comments页面         UpdateComments()        {            List<CMS_site_ext> siteList =);                if (channel != )                {                    CMS_channel parentParentChannel;                    CMS_channel parentChannel;                     m_ChannelDal.Get(parentChannel.parentID);                    }                    CMS_content_ext content = ModelHelper.Convert<CMS_content_ext>(m_ContentDal.GetByChannelID(channel.ID));                    )                    {                        content =  CMS_content_ext();                        content.isNull = /templates/{0}/comments.HTML/{0}/comments.HTML#region GetProcess获取更新进度 ActionResult GetProcess()        {            .IsNullOrWhiteSpace(errMsg))                {                    if (total == )                    {                        total = GetTotal();                        0%                    {                        int percent = (int)(cur / total * 100if (percent == )                        {                            cur = ;                            total = return Content({0}%错误: errMsg);                }            }            #region GetTotal获取进度总数         获取进度总数        <returns></returns>         GetTotal()        {            int channelCount = m_ChannelDal.GetList().Count;            int contentCount = m_ContentDal.GetAllCount();            return channelCount + contentCount + 4#region GetPagelist生成分页数字列表         生成分页数字列表        private List<PageNum> GetPagelist(int currentPage,1)"> pageCount)        {            List<PageNum> result = new List<PageNum>();            result.Add(new PageNum());            if (currentPage > )            {                result.Add());            }            int i = currentPage - 2; i <= currentPage + 2; i++)            {                if (i > 1 && i < pageCount)                {                    result.Add( PageNum(i));                }            }            if (pageCount - currentPage > 3));            }            result.Add( PageNum(pageCount));                }}
VIEw Code

 

总结

以上是内存溢出为你收集整理的自己写的模板引擎,模板生成静态页面全部内容,希望文章能够帮你解决自己写的模板引擎,模板生成静态页面所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1212631.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存