public SetProperty ( String key, Object value ) : void | ||
key | String | |
value | Object | |
Результат | void |
public void ProcessRequest(HttpContext context) { DataBooks book=new DataBooks(); book.name = context.Request["bookname"]; book.type = context.Request["booktype"]; if(book.name!=null) bookcollector.Add(book); context.Response.ContentType = "text/html"; VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); //vltContext.Put("msg", ""); vltContext.Put("bookcollector", bookcollector); vltContext.Put("book", book); Template vltTemplate = vltEngine.GetTemplate("Front/ShopingCar.html");//模版文件所在位置 System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; string username = context.Request.Form["username"]; string password = context.Request.Form["password"]; if (string.IsNullOrEmpty(username) && string.IsNullOrEmpty(password)) { VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); //vltContext.Put("p", person);//设置参数,在模板中可以通过$data来引用 vltContext.Put("username", ""); vltContext.Put("password", ""); vltContext.Put("msg", ""); Template vltTemplate = vltEngine.GetTemplate("Front/login.html");//模版文件所在位置 System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); } else { if (dataaccess(username, password)) { context.Session["username"] = username; context.Response.Redirect("Index.ashx"); } else { VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); //vltContext.Put("p", person);//设置参数,在模板中可以通过$data来引用 vltContext.Put("username", username); vltContext.Put("password", password); vltContext.Put("msg", "用户名密码错误"); Template vltTemplate = vltEngine.GetTemplate("Front/login.html");//模版文件所在位置 System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); } } }
/// <summary> /// 用data数据填充templateName模板,渲染生成html返回 /// </summary> /// <param name="templateName"></param> /// <param name="data"></param> /// <returns></returns> public static string RenderHtml(string templateName, object data) { //第一步:Creating a VelocityEngine也就是创建一个VelocityEngine的实例 VelocityEngine vltEngine = new VelocityEngine(); //也可以使用带参构造函数直接实例 vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); //vltEngine.AddProperty(RuntimeConstants.INPUT_ENCODING, "gb2312"); //vltEngine.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "gb2312"); //第二步:Creating the Template加载模板文件 //这时通过的是Template类,并使用VelocityEngine的GetTemplate方法加载模板 Template vltTemplate = vltEngine.GetTemplate(templateName); //第三步:Merging the template整合模板 VelocityContext vltContext = new VelocityContext(); vltContext.Put("Data", data);//设置参数,在模板中可以通过$data来引用 //第四步:创建一个IO流来输出模板内容推荐使用StringWriter(因为template中以string形式存放) System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); return html; }
public Helper() { vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, AppDomain.CurrentDomain.BaseDirectory); vltEngine.Init(); }
static Program() { VelocityEngine velocity = new VelocityEngine(); velocity.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); velocity.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, @"C:\test\Com.Hertkorn.DevelopmentTree\Com.Hertkorn.DevelopmentTree\template"); velocity.Init(); Engine = velocity; }
public static string readerHtml(string path, string name, object data) { VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath(path));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); vltContext.Put("Data", data);//设置参数,在模板中可以通过$data来引用 Template vltTemplate = vltEngine.GetTemplate(name); System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); return vltWriter.GetStringBuilder().ToString(); }
public void ProcessRequest(HttpContext context) { string searchid= context.Request.Form["searchid"]; string searchtext = context.Request.Form["searchtext"]; dataaccess(searchid, searchtext); if (searchid == "2") { //book context.Response.ContentType = "text/html"; VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); vltContext.Put("object", searchtext); string show="<img src='books/"+book.ser+"' width='210' height='150' />"; vltContext.Put("result", show); Template vltTemplate = vltEngine.GetTemplate("Front/Search.html");//模版文件所在位置 System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); } else if (searchid == "3") { //news context.Response.ContentType = "text/html"; VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); vltContext.Put("object", searchtext); vltContext.Put("result", news.news); Template vltTemplate = vltEngine.GetTemplate("Front/Search.html");//模版文件所在位置 System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); } }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; //创建一个模板引擎 VelocityEngine vltEngine = new VelocityEngine(); //文件型模板,还可以是 assembly ,则使用资源文件 vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); //模板存放目录 vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("/template"));//模板文件所在的文件夹 vltEngine.Init(); //定义一个模板上下文 VelocityContext vltContext = new VelocityContext(); //传入模板所需要的参数 vltContext.Put("Title", "标题"); //设置参数,在模板中可以通过$Title来引用 vltContext.Put("Body", "内容"); //设置参数,在模板中可以通过$Body来引用 vltContext.Put("Date", DateTime.Now); //设置参数,在模板中可以通过$Date来引用 //获取我们刚才所定义的模板,上面已设置模板目录 Template vltTemplate = vltEngine.GetTemplate("basic.html"); System.IO.StringWriter vltWriter = new System.IO.StringWriter(); //根据模板的上下文,将模板生成的内容写进刚才定义的字符串输出流中 vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); ////字符串模板源,这里就是你的邮件模板等等的字符串 //const string templateStr = "$Title,$Body,$Date"; ////创建一个模板引擎 //VelocityEngine vltEngine = new VelocityEngine(); ////文件型模板,还可以是 assembly ,则使用资源文件 //vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); //vltEngine.Init(); ////定义一个模板上下文 //VelocityContext vltContext = new VelocityContext(); ////传入模板所需要的参数 //vltContext.Put("Title", "标题"); //设置参数,在模板中可以通过$Title来引用 //vltContext.Put("Body", "内容"); //设置参数,在模板中可以通过$Body来引用 //vltContext.Put("Date", DateTime.Now); //设置参数,在模板中可以通过$Date来引用 ////定义一个字符串输出流 //StringWriter vltWriter = new StringWriter(); ////输出字符串流中的数据 //vltEngine.Evaluate(vltContext, vltWriter, null, templateStr); //context.Response.Write(vltWriter.GetStringBuilder().ToString()); }
private static void Initialize() { if (!_isInitialized) { lock (lockedObject) { if (!_isInitialized) { engine = new VelocityEngine(); engine.SetProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "NVelocity.Runtime.Log.NullLogSystem"); engine.SetProperty(RuntimeConstants.RESOURCE_MANAGER_CLASS, "NVelocity.Runtime.Resource.ResourceManagerImpl"); engine.SetProperty(RuntimeConstants.COUNTER_NAME, "count"); //engine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH,HttpContext.Current.Server.MapPath("~/files/themes/")); engine.Init(); _isInitialized = true; } } } }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); //vltContext.Put("msg", ""); dataaccess(); vltContext.Put("NewsPool", NewsPool); vltContext.Put("s", new GotNews()); Template vltTemplate = vltEngine.GetTemplate("Front/News.html");//模版文件所在位置 System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); }
/// <summary> /// Initialize the engine with required properties. /// </summary> /// <returns>Engine instance</returns> private static VelocityEngine GetEngine() { NVelocity.App.VelocityEngine engine = new NVelocity.App.VelocityEngine(); //set log class type engine.SetProperty(NVelocity.Runtime.RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, typeof(TemplateEngineLog)); //switch to local context, this way each macro/recursive execution uses its own variables. engine.SetProperty(NVelocity.Runtime.RuntimeConstants.VM_CONTEXT_LOCALSCOPE, "true"); //allows #set to accept null values in the right hand side. engine.SetProperty(NVelocity.Runtime.RuntimeConstants.SET_NULL_ALLOWED, "true"); //set template resource loader to strings engine.SetProperty("resource.loader", "string"); engine.SetProperty("string.resource.loader.class", "NVelocity.Runtime.Resource.Loader.StringResourceLoader"); //engine.SetProperty("string.resource.loader.repository.class", "NVelocity.Runtime.Resource.Util.StringResourceRepositoryImpl"); //initialize engine. engine.Init(); return engine; }
/// <summary> /// Initialize the engine with required properties. /// </summary> /// <returns>Engine instance</returns> private static VelocityEngine GetEngine() { NVelocity.App.VelocityEngine engine = new NVelocity.App.VelocityEngine(); //set log class type engine.SetProperty(NVelocity.Runtime.RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, typeof(TemplateEngineLog)); //switch to local context, this way each macro/recursive execution uses its own variables. engine.SetProperty(NVelocity.Runtime.RuntimeConstants.VM_CONTEXT_LOCALSCOPE, "true"); //allows #set to accept null values in the right hand side. engine.SetProperty(NVelocity.Runtime.RuntimeConstants.SET_NULL_ALLOWED, "true"); //set template resource loader to strings engine.SetProperty("resource.loader", "string"); engine.SetProperty("string.resource.loader.class", "NVelocity.Runtime.Resource.Loader.StringResourceLoader"); //engine.SetProperty("string.resource.loader.repository.class", "NVelocity.Runtime.Resource.Util.StringResourceRepositoryImpl"); //initialize engine. engine.Init(); return(engine); }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); velocityEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("/template")); velocityEngine.Init(); //定义一个模板上下文 VelocityContext velocityContext = new VelocityContext(); //定义类对象 Person p = new Person() { Name = "王三", Age = 20 }; velocityContext.Put("p", p); //定义键值对 Dictionary<string,string> dic=new Dictionary<string, string>(); dic["aa"] = "李四"; dic["bb"] = "30"; velocityContext.Put("dic", dic); //定义list集合 List<string> list=new List<string>(){"张五","马六"}; velocityContext.Put("list", list); //获取定义的模板 Template template = velocityEngine.GetTemplate("baseobject.html"); StringWriter stringWriter = new StringWriter(); template.Merge(velocityContext, stringWriter); string html = stringWriter.GetStringBuilder().ToString(); context.Response.Write(html); }
static NVelocityView() { engine = new VelocityEngine(); engine.SetProperty("resource.loader", "file"); engine.SetProperty("file.resource.loader.path", HttpContext.Current.Server.MapPath("~")); #if DEBUG engine.SetProperty("file.resource.loader.cache", false); #else engine.SetProperty("file.resource.loader.cache", true); engine.SetProperty("file.resource.loader.modificationCheckInterval", 60L); #endif engine.SetProperty("input.encoding", "utf-8"); engine.Init(); }
/// <summary> /// ��ȡ����ģ�����ɵ�ҳ�� /// </summary> /// <param name="fileName">�ļ���</param> /// <param name="vltContext">ģ�����</param> /// <returns></returns> public string GetTemplateString(string fileName, VelocityContext vltContext) { VelocityEngine vltEngine = new VelocityEngine(); // �ļ���ģ��, �������� "assembly", ��ʹ����Դ�ļ� vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); // ģ����Ŀ¼ vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Server.MapPath("~/webim/")); vltEngine.Init(); // ����������ģ��Ŀ¼, �˴������·������. Template vltTemplate = vltEngine.GetTemplate(fileName); StringWriter vltWriter = new StringWriter(); vltTemplate.Merge(vltContext, vltWriter); return vltWriter.GetStringBuilder().ToString(); }
public MenuService(Guid uid) { //权限菜单 user = UserService.instance().GetEntityByID(uid); IEnumerable<Role> roles = RoleService.instance().GetEnumByUID(uid); List<Authority> Authoritys = new List<Authority>(); List<Menu> menus = new List<Menu>(); foreach (var item in roles) { Authoritys.AddRange(AuthorityService.instance().GetAuthorityListByRole(item.ID)); } foreach (var item in Authoritys.GroupBy(m => new { m.PID })) { Menu menu = new Menu(); menu.Name = item.First().ParentAuth.Name; menu.Icon = ""; menu.URL = ""; menu.Type = 1; menu.Childs = new List<Menu>(); var xx = item.OrderBy(m => m.Sort); foreach (var auth in xx) { menu.Childs.Add(new Menu() { Name = auth.Name, URL = auth.Description, Icon = "" }); } menus.Add(menu); } //功能菜单 IEnumerable<Class> classs = ClassService.instance().GetChildByID(Guid.Empty, user.CompanyID).OrderBy(m => m.Sort); foreach (var cl in classs) { Menu menu = new Menu(); menu.Name = cl.Title; menu.Type = cl.Type; menu.Childs = new List<Menu>(); menu.ID = cl.ID; if (cl.Ishaschild) { menu.Type = 1; menu.URL = "#"; cl.Childs.Each(m => { menu.Childs.Add(new Menu() { Name = m.Title, Icon = "", Type = m.Type, ID = m.ID }); }); } menus.Add(menu); } VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, AppDomain.CurrentDomain.BaseDirectory); vltEngine.Init(); var vltContext = new VelocityContext(); vltContext.Put("MENU", menus); Template vltTemplate = vltEngine.GetTemplate("_menu.vm"); var vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); this._html = vltWriter.GetStringBuilder().ToString(); }
public TemplatingService(String templatesPath) { _engine = new VelocityEngine(); _engine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templatesPath); _engine.Init(); }
//public class MyStringTemplateErrorListener : IStringTemplateErrorListener //{ // public void Error(string msg, Exception e) // { // //throw new NotImplementedException(); // } // public void Warning(string msg) // { // //throw new NotImplementedException(); // } //} public override void Generate(StringBuilder builder) { if (db == null || db.Elements == null || db.Elements.Count == 0) return; VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, @"file"); builder.Clear(); // 模板存放目录 vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, @"..\CodeHelper\GenerateUnit\XmlModels"); vltEngine.Init(); // 定义一个模板上下文 VelocityContext vltContext = new VelocityContext(); // 传入模板所需要的参数 //vltContext.Put("Title", "NVelocity 文件模板例子 "); vltContext.Put("model", db); var dict = new Dictionary<string,bool>(); dict.Add("test",true); vltContext.Put("dict", dict); // 获取我们刚才所定义的模板,上面已设置模板目录,此处用相对路径即可 var vltTemplate = vltEngine.GetTemplate("GenSLDomOperClass.gen.cs"); // 定义一个字符串输出流 StringWriter vltWriter = new StringWriter(); // 根据模板的上下文,将模板生成的内容写进刚才定义的字符串输出流中 vltTemplate.Merge(vltContext, vltWriter); // 输出字符串流中的数据 var rr = vltWriter.GetStringBuilder().ToString(); builder.Append(rr); base.Generate(builder); // return; // //var g = new Antlr4.StringTemplate.TemplateGroup(); // //g = Antlr4.StringTemplate.TemplateGroup.DefaultGroup; // ////g.LoadGroupFile(@"..\CodeHelper\GenerateUnit\XmlModels", "GenDomOperClass"); // ////g.LoadGroupFile(@"", @"..\CodeHelper\GenerateUnit\XmlModels\GenDomOperClass"); // ////g.LoadGroupFile(@"D:\workspace\CodeHelper\CodeHelper\GenerateUnit\XmlModels\", @"GenDomOperClass.stg"); // //g.LoadGroupFile("", @"/D:\workspace\CodeHelper\CodeHelper\GenerateUnit\XmlModels\GenDomOperClass.stg"); // //Uri uri = new Uri(@"D:\workspace\CodeHelper\CodeHelper\GenerateUnit\XmlModels\GenDomOperClass.stg"); // var g = new TemplateGroupString(File.ReadAllText(@"D:\workspace\CodeHelper\CodeHelper\GenerateUnit\XmlModels\GenDomOperClass.stg")); // //var g = StringTemplateGroup.LoadGroup(@"..\CodeHelper\GenerateUnit\XmlModels\GenDomOperClass"); // //g.ErrorListener = new MyStringTemplateErrorListener(); // //g..RefreshInterval = new TimeSpan(1000); // builder.Clear(); // var f = db.Elements.ElementAt(0).Fields[0]; // //var gen = g.GetInstanceOf("gen"); // //gen.SetAttribute("model", db); // var gen = g.GetInstanceOf("gen"); // gen.Add("model", db); // var duck = new Duck(); // gen.Add("duck", duck); // //gen.Add("usings", db.UsingNameSpaces); // var r2 = gen.Render(); // builder.Append(r2); // base.Generate(builder); // return; // builder.AppendLine(@"using System; //using System.Collections.Generic; //using System.Linq; //using System.Text; //using CodeHelper.Xml.Core.Nodes; //using System.Xml;"); // var builderUtil = new GeneratorUtil(builder, 0); // builderUtil.AppendLine(); // foreach (var el in db.Elements) // { // Build(el, builderUtil); // builderUtil.AppendLine(); // } }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; string register = context.Request.Form["register"]; if (string.IsNullOrEmpty(register)) { VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); //vltContext.Put("p", person);//设置参数,在模板中可以通过$data来引用 vltContext.Put("error", ""); Template vltTemplate = vltEngine.GetTemplate("Front/register.html");//模版文件所在位置 System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); } else { //先判断用户名是否重复! if (dataaccess(context.Request.Form["username"])) { VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); //vltContext.Put("p", person);//设置参数,在模板中可以通过$data来引用 vltContext.Put("error", "用户名已被注册!"); Template vltTemplate = vltEngine.GetTemplate("Front/register.html");//模版文件所在位置 System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); } else { //这边把数据放到数据库里了! if (datawrite(context.Request.Form["username"], context.Request.Form["password"], context.Request.Form["age"], context.Request.Form["colleage"], context.Request.Form["major"], context.Request.Form["city"], context.Request.Form["pointx"], context.Request.Form["pointy"])) { context.Session["username"] = context.Request.Form["username"]; context.Response.Redirect("Index.ashx"); } else { VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); //vltContext.Put("p", person);//设置参数,在模板中可以通过$data来引用 vltContext.Put("error", "服务器出现错误,请重新注册!"); Template vltTemplate = vltEngine.GetTemplate("Front/register.html");//模版文件所在位置 System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); } } } }
public void ProcessRequest(HttpContext context) { string login = context.Request.Form["login"]; string register = context.Request.Form["register"]; if (context.Session["username"]==null) { if (!string.IsNullOrEmpty(login)) { context.Response.Redirect("Login.ashx"); } else { if (!string.IsNullOrEmpty(register)) { context.Response.Redirect("Register.ashx"); } context.Response.ContentType = "text/html"; VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); string hide = "<div id='start'style='float: right;'><form action='Index.ashx' method='post'><input class='a_demo_four' name='login' type='submit' value='登录'/><input class='a_demo_four' name='register' type='submit' value='注册' /></form></div>"; vltContext.Put("hide", hide); vltContext.Put("show", ""); Template vltTemplate = vltEngine.GetTemplate("Front/Index.html");//模版文件所在位置 System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); } } else { string quit = context.Request.Form["quit"]; if (string.IsNullOrEmpty(quit)) { context.Response.ContentType = "text/html"; VelocityEngine vltEngine = new VelocityEngine(); vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, System.Web.Hosting.HostingEnvironment.MapPath("~/templates"));//模板文件所在的文件夹 vltEngine.Init(); VelocityContext vltContext = new VelocityContext(); //vltContext.Put("p", person);//设置参数,在模板中可以通过$data来引用 //vltContext.Put("username", ""); //vltContext.Put("password", ""); //vltContext.Put("msg", ""); string show = "<div id='start' style='float: right;'><form action='Index.ashx' method='post'><span style='font-size:20px;color:white;background-color:green;'>" + context.Session["username"].ToString() + " 欢迎你!" + "</span><input class='a_demo_four' name='quit' type='submit' value='注销'/></form></div>"; vltContext.Put("show", show); vltContext.Put("hide", ""); Template vltTemplate = vltEngine.GetTemplate("Front/Index.html");//模版文件所在位置 System.IO.StringWriter vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); string html = vltWriter.GetStringBuilder().ToString(); context.Response.Write(html); } else { context.Session.Remove("username"); context.Response.Redirect("Index.ashx"); } } }
/// <summary> /// <p> /// Sets the stylesheet for this transformation set /// </p> /// /// <p> /// Note that don't need this for each document you want /// to transform. Just do it once, and transform away... /// </p> /// </summary> /// <param name="styleReader">Reader with stylesheet char stream</param> public virtual void SetStylesheet(TextReader value) { ready = false; /* * now initialize Velocity - we need to do that * on change of stylesheet */ ve = new VelocityEngine(); /* * if there are user properties, set those first - carefully */ if (velConfig != null) { ConfigureVelocityEngine(ve, velConfig); } /* * register our template() directive */ ve.SetProperty("userdirective", @"NVelocity.Dvsl.Directive.MatchDirective\,NVelocity"); ve.Init(); /* * add our template accumulator */ ve.SetApplicationAttribute("NVelocity.Dvsl.TemplateHandler", templateHandler); /* * load and render the stylesheet * * this sets stylesheet specific context * values */ StringWriter junkWriter = new StringWriter(); styleContext = new VelocityContext(); ve.Evaluate(styleContext, junkWriter, "DVSL:stylesheet", value); /* * now run the base template through for the rules */ // TODO - use ResourceLocator or something else - I don't like the path to the resource Stream s = this.GetType().Assembly.GetManifestResourceStream("NVelocity.Dvsl.Resource.defaultroot.dvsl"); if (s == null) { System.Console.Out.WriteLine("DEFAULT TRANSFORM RULES NOT FOUND "); } else { ve.Evaluate(new VelocityContext(), junkWriter, "defaultroot.dvsl", new StreamReader(s)); s.Close(); } /* * need a new transformer, as it depends on the * velocity engine */ transformer = new Transformer(ve, templateHandler, baseContext, appVals, validate); }
public TemplatingService() { _engine = new VelocityEngine(); _engine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "App_Data\\Templates")); _engine.Init(); }
/// <summary> /// <p> /// Add mapped properties from hashtable on VelocityEngine. /// </p> /// <p> /// If you are going to use this, ensure you do it *before* setting /// the stylesheet, as that creates the VelocityEngine /// </p> /// </summary> private void ConfigureVelocityEngine(VelocityEngine ve, Hashtable map) { if (ve == null || map == null) { return ; } foreach (DictionaryEntry entry in map) { ve.SetProperty((String)entry.Key, entry.Value); } }
// public virtual ExtendedProperties GetContextProperties() { // return contextProperties; // } // // public virtual bool UseClasspath { // set { // this.useClasspath = value; // } // } /// <summary> /// Execute the input script with Velocity /// @throws BuildException /// BuildExceptions are thrown when required attributes are missing. /// Exceptions thrown by Velocity are rethrown as BuildExceptions. /// </summary> protected override void ExecuteTask() { // Make sure the template path is set. if (templatePath == null && useClasspath == false) { throw new BuildException("The template path needs to be defined if you are not using " + "the classpath for locating templates!"); } // Make sure the control template is set. if (controlTemplate == null) { throw new BuildException("The control template needs to be defined!"); } // Make sure the output directory is set. if (outputDirectory == null) { throw new BuildException("The output directory needs to be defined!"); } // Make sure there is an output file. if (outputFile == null) { throw new BuildException("The output file needs to be defined!"); } VelocityEngine ve = new VelocityEngine(); try { // Setup the Velocity Runtime. if (templatePath != null) { //log("Using templatePath: " + templatePath, project.MSG_VERBOSE); Log.WriteLine(LogPrefix + "Using templatePath: " + templatePath); ve.SetProperty(RuntimeConstants_Fields.FILE_RESOURCE_LOADER_PATH, templatePath); } if (useClasspath) { Log.WriteLine(LogPrefix + "Using classpath"); ve.AddProperty(RuntimeConstants_Fields.RESOURCE_LOADER, "classpath"); ve.SetProperty("classpath." + RuntimeConstants_Fields.RESOURCE_LOADER + ".class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); ve.SetProperty("classpath." + RuntimeConstants_Fields.RESOURCE_LOADER + ".cache", "false"); ve.SetProperty("classpath." + RuntimeConstants_Fields.RESOURCE_LOADER + ".modificationCheckInterval", "2"); } ve.Init(); // Create the text generator. Generator generator = Generator.Instance; generator.LogPrefix = LogPrefix; generator.VelocityEngine = ve; generator.OutputPath = outputDirectory; generator.InputEncoding = inputEncoding; generator.OutputEncoding = outputEncoding; if (templatePath != null) { generator.TemplatePath = templatePath; } // Make sure the output directory exists, if it doesn't // then create it. System.IO.FileInfo file = new System.IO.FileInfo(outputDirectory); bool tmpBool; if (System.IO.File.Exists(file.FullName)) tmpBool = true; else tmpBool = System.IO.Directory.Exists(file.FullName); if (!tmpBool) { System.IO.Directory.CreateDirectory(file.FullName); } System.String path = outputDirectory + System.IO.Path.DirectorySeparatorChar.ToString() + outputFile; Log.WriteLine(LogPrefix + "Generating to file " + path); System.IO.StreamWriter writer = generator.getWriter(path, outputEncoding); // The generator and the output path should // be placed in the init context here and // not in the generator class itself. IContext c = initControlContext(); // Everything in the generator class should be // pulled out and placed in here. What the generator // class does can probably be added to the Velocity // class and the generator class can probably // be removed all together. populateInitialContext(c); // Feed all the options into the initial // control context so they are available // in the control/worker templates. if (contextProperties != null) { IEnumerator i = contextProperties.Keys; while (i.MoveNext()) { System.String property = (System.String) i.Current; System.String value_Renamed = contextProperties.GetString(property); // Now lets quickly check to see if what // we have is numeric and try to put it // into the context as an Integer. try { c.Put(property, System.Int32.Parse(value_Renamed)); } catch (System.FormatException nfe) { // Now we will try to place the value into // the context as a boolean value if it // maps to a valid boolean value. System.String booleanString = contextProperties.TestBoolean(value_Renamed); if (booleanString != null) { c.Put(property, booleanString.ToUpper().Equals("TRUE")); } else { // We are going to do something special // for properties that have a "file.contents" // suffix: for these properties will pull // in the contents of the file and make // them available in the context. So for // a line like the following in a properties file: // // license.file.contents = license.txt // // We will pull in the contents of license.txt // and make it available in the context as // $license. This should make texen a little // more flexible. if (property.EndsWith("file.contents")) { // We need to turn the license file from relative to // absolute, and let Ant help :) //value_Renamed = StringUtils.fileContentsToString(project.resolveFile(value_Renamed).CanonicalPath); value_Renamed = StringUtils.fileContentsToString(new FileInfo(value_Renamed).FullName); property = property.Substring(0, (property.IndexOf("file.contents") - 1) - (0)); } c.Put(property, value_Renamed); } } } } writer.Write(generator.parse(controlTemplate, c)); writer.Flush(); writer.Close(); generator.shutdown(); cleanup(); } catch (BuildException e) { throw e; } catch (MethodInvocationException e) { throw new BuildException("Exception thrown by '" + e.ReferenceName + "." + e.MethodName + "'" + ERR_MSG_FRAGMENT, e.WrappedThrowable); } catch (ParseErrorException e) { throw new BuildException("Velocity syntax error" + ERR_MSG_FRAGMENT, e); } catch (ResourceNotFoundException e) { throw new BuildException("Resource not found" + ERR_MSG_FRAGMENT, e); } catch (System.Exception e) { throw new BuildException("Generation failed" + ERR_MSG_FRAGMENT, e); } }