以前写java的时候就velocity ,人家问偶struts的时候嘿嘿,只知道eclipse是可以配置的,其他木然
最近被迫写c#,也顺手找到了下,发现nvelocity 估计以后人家问偶webui的时候也只有继续木然了。

借鉴前人的,改了下。
测试下来速度还是可以的

目标

基础接口,写php弄smarty留下来遗产,java在用,c#也就继续下去吧。

 TemplateBase : ITemplateParse
    {
        private string _templateDir;
        
private string _configDir;
        
private string _cacheDir;
        
private bool _caching;
        
private bool _debugging;
        
public abstract void Assign(string key, object value);
        
public bool IsCached(string templateFileName, string catchId, string compareId)
        {
            
throw new System.NotImplementedException();
        }

        
public virtual void Display(string templateFileName)
        {
            
throw new System.NotImplementedException();
        }

        
public virtual string TemplateDir
        {
            
get { return _templateDir; }
            
set { _templateDir = value; }
        }

        
public virtual string ConfigDir
        {
            
get { return _configDir; }
            
set { _configDir = value; }
        }

        
public virtual string CacheDir
        {
            
get { return _cacheDir; }
            
set { _cacheDir = value; }
        }

        
public virtual bool Caching
        {
            
get { return _caching; }
            
set { _caching = value; }
        }

        
public virtual bool Debugging
        {
            
get { return _debugging; }
            
set { _debugging = value; }
        }
    }
}

 

//没有把缓存的贴出来,写着写忘记了从新建了class。娃哈哈。

 VelocityHelper : TemplateBase
    {
        private VelocityEngine velocity;
        
private IContext context = new VelocityContext();


        
/// <summary>
        
/// 给模板变量赋值
        
/// </summary>
        
/// <param name="key">
        
/// 变量名称
        
/// </param>
        public override void Assign(string key, object value)
        {
            
if (context == null)
                context 
= new VelocityContext();
            context.Put(key, value);
        }
        
/// <summary>
        
///  显示模板
        
/// </summary>
        
/// <param name="templateFileName"></param>
        public override void Display(string templateFileName)
        {
            
//TODO  检查目录是否初始化过
            if (TemplateDir == null)
                TemplateDir 
= "";//


            
//创建VelocityEngine实例对象
            velocity = new VelocityEngine();

            
//使用设置初始化VelocityEngine
            ExtendedProperties props = new ExtendedProperties();
            props.AddProperty(RuntimeConstants.RESOURCE_LOADER, 
"file");
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, HttpContext.Current.Server.MapPath(TemplateDir));
            
//props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateDir);


            props.AddProperty(RuntimeConstants.INPUT_ENCODING, 
"utf-8");
            props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, 
"utf-8");
            velocity.Init(props);

            
//从文件中读取模板
            var template = velocity.GetTemplate(templateFileName);

            
//合并模板
            StringWriter writer = new StringWriter();
            template.Merge(context, writer);
            writer.Close();

            
//输出我页面
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(writer.ToString());
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();



        }
    }
 }

 

 

下面是生成静态页面的东东,估计是上面那个是吃中午饭前完成的。下面是吃完饭回来写,哎,人老了。

接口:

    }

 

不知道怎么发晕了,又从新写了nvelocity 解析的类

 NVelocityCacher:IHtmlCacher
    {
        private VelocityEngine velocity;
        
private IContext context = new VelocityContext();
        
private System.Collections.Hashtable resolverMap = new Hashtable();


        
public NVelocityCacher()
        {
            
if (context==null)
            {
                context 
= new VelocityContext();
            }
        }
        
/// <summary>
        
///  加载不同页面解析器
        
/// </summary>
        
/// <param name="key"></param>
        
/// <param name="resolver"></param>
        public void AddAResolver(string key,BaseHtmlCacheResolver resolver)
        {
            resolverMap.Add(key,resolver);
        }

        
/// <summary>
        
/// 创建缓存文件
        
/// </summary>
        
/// <param name="templatePath"></param>
        
/// <param name="templateFileName"></param>
        
/// <param name="outDir"></param>
        
/// <param name="outFileName"></param>
        
/// <param name="cacherInfo"></param>
        
/// <returns></returns>
        public int CreateCacheFile(string templatePath, string templateFileName,string outDir,string outFileName,CacherInfo cacherInfo)
        {                      
            
//创建VelocityEngine实例对象
            velocity = new VelocityEngine();

            
//使用设置初始化VelocityEngine
            ExtendedProperties props = new ExtendedProperties();
            props.AddProperty(RuntimeConstants.RESOURCE_LOADER, 
"file");
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templatePath);
            
//props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateDir);


            props.AddProperty(RuntimeConstants.INPUT_ENCODING, 
"utf-8");
            props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, 
"utf-8");
            velocity.Init(props);

            
//从文件中读取模板
            var template = velocity.GetTemplate(templateFileName);


            
//遍历解析器
            foreach (System.Collections.DictionaryEntry ob in resolverMap)
            {
                context.Put(ob.Key.ToString(),ob.Value);
            }
            context.Put(
"SysPage", cacherInfo);//TODO 把页面公用信息,和本身标示放进去
            
//合并模板
            StringWriter writer = new StringWriter();
            template.Merge(context, writer);

            
//生成静态页
            string cacheDir = outDir + "/" + outFileName;//TODO 这里有问题需要修改
            using (StreamWriter writer2 = new StreamWriter(cacheDir,false,Encoding.UTF8,200))
            {
                writer2.Write(writer); 
                writer2.Flush();
                writer2.Close();
            }           
            
return 0;
        }

        
/// <summary>
        
///  显示模板
        
/// </summary>
        
/// <param name="TemplateDir"></param>
        
/// <param name="templateFileName"></param>
        
/// <param name="cacherInfo"></param>
        public void PreviewCacheFile(string TemplateDir, string templateFileName,CacherInfo cacherInfo)
        {
            
//TODO  检查目录是否初始化过
            if (TemplateDir.IndexOf("~"== 0)
                TemplateDir 
= HttpContext.Current.Server.MapPath(TemplateDir);

            
if (!System.IO.Directory.Exists(TemplateDir))
            {
                
string er = "模板路径不存在!! path=" + TemplateDir;
                
throw new Exception(er);
            }
            
if (!System.IO.File.Exists(TemplateDir + "/"+templateFileName))
            {
                
string er = "模板不存在!! path=" + TemplateDir + "/" + templateFileName;
                
throw new Exception(er);
            }

            
//创建VelocityEngine实例对象
            velocity = new VelocityEngine();

            
//使用设置初始化VelocityEngine
            ExtendedProperties props = new ExtendedProperties();
            props.AddProperty(RuntimeConstants.RESOURCE_LOADER, 
"file");
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateDir);
            
//props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateDir);


            props.AddProperty(RuntimeConstants.INPUT_ENCODING, 
"utf-8");
            props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, 
"utf-8");
            velocity.Init(props);

            
//从文件中读取模板
            var template = velocity.GetTemplate(templateFileName);


            
//遍历解析器
            foreach (System.Collections.DictionaryEntry ob in resolverMap)
            {
                context.Put(ob.Key.ToString(), ob.Value);
            }
            context.Put(
"SysPage", cacherInfo);
            
//合并模板
            StringWriter writer = new StringWriter();
            template.Merge(context, writer);



            
//输出我页面
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(writer.ToString());
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }
    }

 

使用的方法:

 HtmlMaker
    {
        #region 私有变量

        
private IHtmlCacher _htmlCather;
        
#endregion

        
#region 实现现成安全的singleton
        
private HtmlMaker()
        {
            
this.InitHtmlMaker();
        }

        
public static HtmlMaker Instance
        {
            
get
            {
                
return Singleton.htmlMaker;
            }

        }

        
private class Singleton
        {
            
static Singleton()
            {

            }
            
internal static readonly HtmlMaker htmlMaker =
              
new HtmlMaker();
        }
        
#endregion




        
#region 基本方法
        
private void InitHtmlMaker()
        {
            _htmlCather 
= new NVelocityCacher();
            
/*  把你想要加载的东西放这里 
              //TODO 以后改成读配置文件,检查名称唯一性
            var catalogResolver = new CatalogListCacheResolver();
            _htmlCather.AddAResolver("catalog", catalogResolver);
             
*/


        }
        
#endregion

        
public void UpdateCache(string tplPath,string tplName,string outPath,string outName,CacherInfo cacherInfo)
        {
            _htmlCather.CreateCacheFile(tplPath, tplName, outPath, outName, cacherInfo);
        }

        
public void PreviewCacheFile(string tplpath,string tplName,CacherInfo cacherInfo)
        {
            _htmlCather.PreviewCacheFile(tplpath, tplName, cacherInfo);
        }

        
public void PreviewCacheFile(string fileFullPath, CacherInfo cacherInfo)
        {
            
if(fileFullPath.IndexOf("~")==0)
                fileFullPath 
= HttpContext.Current.Server.MapPath(fileFullPath);

            
if (!System.IO.File.Exists(fileFullPath))
            {  
                
string er = "模板路径不存在!! path=" + fileFullPath;
                
throw new Exception(er);
            }
            
string tplPath = System.IO.Path.GetDirectoryName(fileFullPath);
            
string tplName = fileFullPath.Replace(tplPath, "");

            _htmlCather.PreviewCacheFile(tplPath, tplName, cacherInfo);
        }

        
public void CreateCacheFile(string fileFullPath, string outFullPath, CacherInfo cacherInfo)
        {
            
//*1*模板处理
            if (fileFullPath.IndexOf("~"== 0)
                fileFullPath 
= HttpContext.Current.Server.MapPath(fileFullPath);

            
if (!System.IO.File.Exists(fileFullPath))
            {
                
string er = "模板路径不存在!! path=" + fileFullPath;
                
throw new Exception(er);
            }
            
string tplPath = System.IO.Path.GetDirectoryName(fileFullPath);
            
string tplName = System.IO.Path.GetFileName(fileFullPath);

            
//*2*输出
            if (outFullPath.IndexOf("~"== 0)
                outFullPath 
= HttpContext.Current.Server.MapPath(outFullPath);

  
            
string outPath = System.IO.Path.GetDirectoryName(outFullPath);
            
string outName = System.IO.Path.GetFileName(outFullPath);

            
if (!System.IO.Directory.Exists(outPath))
            {
                
try
                {
                    System.IO.Directory.CreateDirectory(outPath);
                }
                
catch
                {
                    
string er = "无法创建缓存目录!! path=" + outPath;
                    
throw new Exception(er);
                }
            }

            _htmlCather.CreateCacheFile(tplPath, tplName, outPath, outName, cacherInfo);
        }

        
public void CreateCacheFile(string fileFullPath,string outPath,string outName,CacherInfo cacherInfo)
        {
            
//*1*模板处理
            if (fileFullPath.IndexOf("~"== 0)
                fileFullPath 
= HttpContext.Current.Server.MapPath(fileFullPath);

            
if (!System.IO.File.Exists(fileFullPath))
            {
                
string er = "模板路径不存在!! path=" + fileFullPath;
                
throw new Exception(er);
            }
            
string tplPath = System.IO.Path.GetDirectoryName(fileFullPath);
            
string tplName = fileFullPath.Replace(tplPath, "");
            
            
//*2*输出处理
            if(outPath.IndexOf("~")==0)
            {
                outPath 
= HttpContext.Current.Server.MapPath(outPath);
            }
            
if(!System.IO.Directory.Exists(outPath))
            {
                System.IO.Directory.CreateDirectory(outPath);
            }

            _htmlCather.CreateCacheFile(tplPath, tplName, outPath, outName,cacherInfo); 
        }
    }

 

2个补充类,一个示例类,一个模板。

 

 BaseHtmlCacheResolver
    {
        private readonly Service.IServiceFactory _serviceFactory =   My.Service.Imp.ServiceFactory.Instance;//把Service factory加载起来大家用

        
protected LDCMS.Core.Service.IServiceFactory ServiceFatory
        {
            
get
            {      
                
return _serviceFactory;
            }
        }
    }

//用于存储全局使用的变量
 public class CacherInfo
    {
//随便放点你需要放置的全局要用的东西
}

//一个实现类
  public class CatalogListCacheResolver:BaseHtmlCacheResolver
    {

        
private LDCMS.Core.Service.ICatalogService _catalogService;

        
public CatalogListCacheResolver()
        {
            _catalogService 
= ServiceFatory.getCatalogManager();
        }


        
//示例

         
public Catalog GetCatalog(int id)
        {
             
return _catalogService.GetById(id);
        }
}


//html.vm
#set($entity = $catalog.GetCatalog(1))
栏目名称:$entity.Name
</b>
栏目位置:$entity.Link
</b>

 

 

先用着吧。

不过nvelocity 全局宏还是不知道怎么加载。头痛中

 nvelcotiy 用的是castle的。他的关于宏的包还木弄明白。

至于spring 这个东西哎。。spring.net 还木弄明白的,所以spring+velocity+hibernate这个东西可能不太可能翻译成
spring.net+nvelocity+nhibernate了。不过junit log4j 变成nunit,log4net 还在继续发挥他们功能。
有空再把他们2个抓来show下。

 

 

相关文章:

  • 2021-11-27
  • 2021-06-04
  • 2022-12-23
  • 2022-12-23
  • 2022-01-28
  • 2021-06-28
  • 2021-10-20
猜你喜欢
  • 2021-09-30
  • 2022-12-23
  • 2022-12-23
  • 2021-11-29
  • 2021-09-25
  • 2021-05-31
  • 2021-10-06
相关资源
相似解决方案