现在的位置: 首页 > 综合 > 正文

模板机制的第一个程序Hello World

2011年02月01日 ⁄ 综合 ⁄ 共 1350字 ⁄ 字号 评论关闭
很简单,但是终于还是弄出来了~
用的StringTemplate模板引擎~原本模板是写在.cs里面的,分离出来之后感觉速度慢了不少....估计要缓存吧~不知道还有更好的建议没有

模板页

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
    
<head>
        
<title>$title$</title>
    
</head>
    
<body>
        $var$
    
</body>
</html>

.aspx页面

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TemplateTest._Default" %>

.cs页面

using System;
using System.Web;
using Antlr.StringTemplate;
using System.IO;
//using Antlr.StringTemplate.Language;
//using antlr.collections;

namespace TemplateTest
{
    
public partial class _Default : System.Web.UI.Page
    {
        
protected void Page_Load(object sender, EventArgs e)
        {
            StringTemplate st 
= new StringTemplate(Read("default.htm"));
            st.SetAttribute(
"title""第一个示例");
            st.SetAttribute(
"var""Hello World");
            Response.Write(st.ToString());
        }

        public static string Read(string filename)
        {

            filename = HttpContext.Current.Server.MapPath("~/Template/" + filename);
            
using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                StreamReader sr 
= new StreamReader(fs);
                
return sr.ReadToEnd();
            }

        }

    }
}

还有效果图

抱歉!评论已关闭.