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 static string RenderView(this HtmlHelper html, string viewName, string sectionName, IDictionary parameters) { if (!string.IsNullOrEmpty(sectionName)) { viewName += ":" + sectionName; } var velocityView = html.ViewContext.View as NVelocityView; if (velocityView == null) throw new InvalidOperationException("The RenderView extension can only be used from views that were created using NVelocity."); var newContext = velocityView.Context; if (parameters != null && parameters.Keys.Count > 0) { // Clone the existing context and then add the custom parameters newContext = new VelocityContext(); foreach (var key in velocityView.Context.Keys) { newContext.Put((string)key, velocityView.Context.Get((string)key)); } foreach (var key in parameters.Keys) { newContext.Put((string)key, parameters[key]); } } // Resolve the template and render it. The partial resource loader takes care of validating // the view name and extracting the partials. var template = velocityView.Engine.GetTemplate(viewName); using (var writer = new StringWriter()) { template.Merge(newContext, writer); return writer.ToString(); } }
/// <summary> /// This test starts a VelocityEngine for each execution /// </summary> public void ExecuteMethodUntilSignal1() { startEvent.WaitOne(int.MaxValue, false); while(!stopEvent.WaitOne(0, false)) { VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.Init(); StringWriter sw = new StringWriter(); VelocityContext c = new VelocityContext(); c.Put("x", new Something()); c.Put("items", items); bool ok = velocityEngine.Evaluate(c, sw, "ContextTest.CaseInsensitive", @" #foreach( $item in $items ) $item, #end "); Assert.IsTrue(ok, "Evaluation returned failure"); Assert.AreEqual("a,b,c,d,", Normalize(sw)); } }
public void RenderTemplate(string templateName, object model) { string templateFullPath = applicationInfo.AbsolutizePath("Web/Pages/Templates/" + templateName + ".vm.html"); ITemplateSource template = new CacheableFileTemplate( templateFullPath, fileCache); string templateText = template.GetTemplate(); VelocityEngine velocity = new VelocityEngine(); velocity.Init(); VelocityContext velocityContext = new VelocityContext(); velocityContext.Put("m", model); velocityContext.Put("h", this); using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { if (false == velocity.Evaluate(velocityContext, stringWriter, null, templateText)) throw new InvalidOperationException("Template expansion failed"); writer.InnerWriter.Write(stringWriter.ToString()); } writer.WriteLine(); }
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); } } }
private IContext CreateVelocityContext(object model) { var velocityContext = new VelocityContext(); if (model != null) velocityContext.Put("model", model); velocityContext.Put("vel", this); velocityContext.Put("html", new HtmlHelper()); return velocityContext; }
public static void Main(System.String[] args) { // first, we init the runtime engine. Defaults are fine. try { Velocity.Init(); } catch (System.Exception e) { System.Console.Out.WriteLine("Problem initializing Velocity : " + e); return; } // lets make a Context and put data into it VelocityContext context = new VelocityContext(); context.Put("name", "Velocity"); context.Put("project", "Jakarta"); // lets render a template StringWriter writer = new StringWriter(); try { Velocity.MergeTemplate("example2.vm", context, writer); } catch (System.Exception e) { System.Console.Out.WriteLine("Problem merging template : " + e); } System.Console.Out.WriteLine(" template : " + writer.GetStringBuilder().ToString()); // lets dynamically 'create' our template // and use the evaluate() method to render it System.String s = "We are using $project $name to render this."; writer = new StringWriter(); try { Velocity.Evaluate(context, writer, "mystring", s); } catch (ParseErrorException pee) { // thrown if something is wrong with the // syntax of our template string System.Console.Out.WriteLine("ParseErrorException : " + pee); } catch (MethodInvocationException mee) { // thrown if a method of a reference // called by the template // throws an exception. That won't happen here // as we aren't calling any methods in this // example, but we have to catch them anyway System.Console.Out.WriteLine("MethodInvocationException : " + mee); } catch (System.Exception e) { System.Console.Out.WriteLine("Exception : " + e); } System.Console.Out.WriteLine(" string : " + writer.GetStringBuilder().ToString()); }
private VelocityContext CreateTemplateContext(ProcessURI uri, IProcessResponse response, Domain domain) { VelocityContext context = new VelocityContext(); context.Put("uri", uri); context.Put("renderer", this); if (response != null) context.Put("response", response); if (domain != null) context.Put("domain", domain); foreach (RendererHelper helper in Helpers) context.Put(helper.Name, helper); return context; }
public string FormatUserEntry(User user, ISettings settings, string template) { var context = new VelocityContext(); context.Put("user", user); context.Put("settings", settings); using (StringWriter writer = new StringWriter()) { template = PrepareTemplate(template); _engine.Evaluate(context, writer, null, template); return writer.ToString(); } }
public String GetTemplatedDocument(String templateName, IDictionary<String, String> data, IDictionary<String, object[]> list = null) { Template template = _engine.GetTemplate(templateName); VelocityContext context = new VelocityContext(); data.Keys.ToList().ForEach(k => context.Put(k, data[k])); if (list != null) context.Put(list.Keys.FirstOrDefault(), list.Values.FirstOrDefault()); StringWriter writer = new StringWriter(); template.Merge(context, writer); return writer.ToString(); }
public string GetRealMessage(BaseRequest request, Response response) { var baseMessage = GetBaseMessage(); if (baseMessage == null) return null; var context = new VelocityContext(); context.Put("request", request); context.Put("response", response); var result = new StringWriter(); Velocity.Evaluate(context, result, "", baseMessage); return result.ToString(); }
/// <exception cref="ArgumentException"></exception> string BuildEmail(string templateName, IDictionary<string, object> viewdata) { if (viewdata == null) { throw new ArgumentNullException("viewData"); } if (string.IsNullOrEmpty(templateName)) { throw new ArgumentException("TemplateName"); } var template = ResolveTemplate(templateName); var context = new VelocityContext(); foreach (var key in viewdata.Keys) { context.Put(key, viewdata[key]); } using (var writer = new StringWriter()) { template.Merge(context, writer); return writer.ToString(); } }
/// <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 static string FormatText(string templateText, IDictionary<string,object> values) { var nvelocityContext = new VelocityContext(); foreach (var tagValue in values) nvelocityContext.Put(tagValue.Key, tagValue.Value); return FormatText(templateText, nvelocityContext); }
/// <summary>The format.</summary> /// <param name="text">The text.</param> /// <param name="items">The items.</param> /// <returns>The format.</returns> /// <exception cref="TemplateException"></exception> public string Format(string text, Dictionary<string, object> items) { try { VelocityContext velocityContext = new VelocityContext(); if (items != null) { foreach (var pair in items) { velocityContext.Put(pair.Key, pair.Value); } } StringWriter sw = new StringWriter(); VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.Init(); bool ok = velocityEngine.Evaluate(velocityContext, sw, "ContextTest.CaseInsensitive", text); if (!ok) { throw new TemplateException("Template run error (try adding an extra newline at the end of the file)"); } return sw.ToString(); } catch (ParseErrorException parseErrorException) { throw new TemplateException(parseErrorException.Message, parseErrorException); } }
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 string GenerateReport(string pathToLIFT) { Velocity.Init(); VelocityContext context = new VelocityContext(); context.Put("pathToLift", pathToLIFT); XPathChart chart = new XPathChart(); context.Put("chart", chart); chart.PathToXmlDocument = pathToLIFT; try { string dir = Path.Combine(Path.GetTempPath(), "WeSayReport"); if (Directory.Exists(dir)) { Directory.Delete(dir, true); } Directory.CreateDirectory(dir); string path = Path.Combine(dir, "WeSayReport.htm"); // File.Copy("chart.png", Path.Combine(dir, "chart.png")); context.Put("foo", new Foo(dir)); using (StreamWriter stream = File.CreateText(path)) { /*I couldn't get nvelocity to read directly from the resource*/ string templatePath = Path.Combine(Path.GetTempPath(), "tempReportTemplate.vm"); File.WriteAllText(templatePath, Resources.reportTemplate); //hack to get around weird Velocity problem; if I give it the //full path into temp, it chokes saying it can't handle the path format string oldCurrentDir = Directory.GetCurrentDirectory(); Directory.SetCurrentDirectory(Path.GetTempPath()); Template template = Velocity.GetTemplate(Path.GetFileName(templatePath)); Directory.SetCurrentDirectory(oldCurrentDir); template.Merge(context, stream); File.Delete(templatePath); } return path; } catch (Exception e) { ErrorReport.ReportNonFatalMessage("Problem creating report : " + e); } return null; }
/// <summary> /// The parse. /// </summary> /// <param name="template"> /// The template. /// </param> /// <param name="model"> /// The model. /// </param> /// <returns> /// The System.String. /// </returns> public string Parse(string template, dynamic model) { var ctx = new VelocityContext(); ctx.Put("Model", model); var writer = new StringWriter(); VelocityEngine.Evaluate(ctx, writer, null, template); return writer.GetStringBuilder().ToString(); }
private static VelocityContext GetContextFromDictionary(Dictionary<string, object> param) { VelocityContext context = new VelocityContext(); foreach (KeyValuePair<string, object> pair in param) { context.Put(pair.Key, pair.Value); } return context; }
public String GetTemplatedDocument(String templateName, IDictionary<String, String> data) { Template template = _engine.GetTemplate(templateName); VelocityContext context = new VelocityContext(); data.Keys.ToList().ForEach(k => context.Put(k, data[k])); StringWriter writer = new StringWriter(); template.Merge(context, writer); return writer.ToString(); }
private VelocityContext GetContext(Dictionary<string, object> data) { var context = new VelocityContext(); foreach (KeyValuePair<string, object> pair in data) { context.Put(pair.Key, pair.Value); } return context; }
static HtmlGenerator() { velocity = new VelocityEngine(); var p = new Commons.Collections.ExtendedProperties(); #if DEBUG string temp = Application.ExecutablePath; string[] split = Application.ExecutablePath.Split('\\'); string pathRoot = string.Join("\\", split, 0, split.Length - 3); //cssFile = string.Format(@"file:///{0}\html\best.css", pathRoot); //scriptFile = string.Format(@"file:///{0}\html\scripts.js", pathRoot); p.AddProperty("file.resource.loader.path", new System.Collections.ArrayList(new string[] { pathRoot })); #endif velocity.Init(p); baseContext = new VelocityContext(); baseContext.Put("script", "scripts.js"); baseContext.Put("css", "best.css"); }
public string TransformTemplate(IDictionary<string,object> templateData, string template) { if (templateData == null) throw new ArgumentNullException("templateData"); var context = new VelocityContext(); foreach(var dataItem in templateData) context.Put(dataItem.Key, dataItem.Value); return ApplyTemplate(template, context); }
public static string AsNVelocityTemplate(this Dictionary<string, object> inputs, TemplateEnum template) { var context = new VelocityContext(); foreach (var input in inputs) { context.Put(input.Key, input.Value); } return NVelocityConfig.MergeTemplate(context, template); }
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()); }
/// <summary> /// Generate an ActiveRecord model usable by the Castle Project's /// ActiveRecord library /// </summary> /// <param name="p_Table">database table or view name</param> /// <param name="p_OutputDir">the target directory</param> public void GenerateClass(string sTemplate, DbTableInfo p_Table, string p_OutputDir) { Template template = engine.GetTemplate(sTemplate); // Generate ActiveRecord Classes string className = p_Table.GetClassName(); DbFieldInfo[] fieldList = p_Table.GetFields(); DbRelatedTableInfo[] related = p_Table.GetDbRelatedTableInfo(); // replicate flag to children //TODO: add to [new] code generation context for (int i = 0; i < fieldList.Length; i++) { fieldList[i].EnableValidationAttributes = _EnableValidationAttributes; } Debug.WriteLine("Table: " + p_Table + " -> " + className); string fileName; VelocityContext context = new VelocityContext(); context.Put("namespace", _NameSpace); context.Put("developer", Environment.UserName); context.Put("Partial", _MakePartial ? "partial" : ""); context.Put("PropChange", _PropChange); context.Put("table", p_Table); context.Put("fields", fieldList); context.Put("related", related); context.Put("date", DateTime.Now.ToString("yyyy-MM-dd")); //get suggested class name fileName = GetFileName(sTemplate, context); if (!CanWriteThisFile(p_OutputDir, className, fileName)) return; StreamWriter wr = new StreamWriter(p_OutputDir + fileName); try { StringWriter writer = new StringWriter(); template.Merge(context, writer); wr.WriteLine(writer.GetStringBuilder().ToString()); } finally { wr.Close(); } }
/// ------------------------------------------------------------------------------------ /// <summary> /// Initializes a new instance of the <see cref="FdoGenerate"/> class. /// </summary> /// <param name="doc">The XMI document.</param> /// <param name="outputDir">The output dir.</param> /// <param name="outputFile">The output file name.</param> /// ------------------------------------------------------------------------------------ public FdoGenerateImpl(XmlDocument doc, string outputDir, string outputFile) { Generator = this; m_Document = doc; m_OutputDir = outputDir; m_OutputFileName = outputFile; var entireModel = (XmlElement)doc.GetElementsByTagName("EntireModel")[0]; m_Model = new Model(entireModel); m_Engine = new VelocityEngine(); m_Engine.Init(); m_Context = new VelocityContext(); m_Context.Put("fdogenerate", this); m_Context.Put("model", m_Model); RuntimeSingleton.RuntimeServices.SetApplicationAttribute("FdoGenerate.Engine", m_Engine); RuntimeSingleton.RuntimeServices.SetApplicationAttribute("FdoGenerate.Context", m_Context); }
public static string Fill(this string s, object param) { var context = new VelocityContext(); foreach (var prop in param.GetType().GetProperties()) context.Put(prop.Name, prop.GetValue(param, null)); using (var tw = new StringWriter()) { engine.Evaluate(context, tw, "", s); return tw.ToString(); } }
private static IContext GetContext(IEnumerable<KeyValuePair<string, object>> data) { var context = new VelocityContext(); foreach (var d in data) { context.Put(d.Key, d.Value); } return context; }
public void PopulateTemplatesWithCurrentCategories() { Console.WriteLine("*** PopulateTemplatesWithCurrentCategories"); Category[] categories = Category.FindAll(); foreach (Category category in categories) { CastlePortal.Template template = category.Template; Console.WriteLine("Template:" + template.Id +","+ template.Name); string path = Path.Combine(TestsCommons.TEMPLATESDIR, TestsCommons.GENERALTEMPLATES); path = Path.Combine(path, template.Name); path += TestsCommons.EXTENSION; NVelocity.Template nvtemplate = velocity.GetTemplate(path); VelocityContext context = new VelocityContext(); context.Put(TestsCommons.TEMPLATESDIRVAR, TestsCommons.TEMPLATESDIR); context.Put(TestsCommons.CATEGORYVAR, category); StringWriter writer = new StringWriter(); nvtemplate.Merge(context, writer); } }
public Example1(System.String templateFile) { try { /* * setup */ Velocity.Init("nvelocity.properties"); /* * Make a context object and populate with the data. This * is where the Velocity engine gets the data to resolve the * references (ex. $list) in the template */ VelocityContext context = new VelocityContext(); context.Put("list", Names); /* * get the Template object. This is the parsed version of your * template input file. Note that getTemplate() can throw * ResourceNotFoundException : if it doesn't find the template * ParseErrorException : if there is something wrong with the VTL * Exception : if something else goes wrong (this is generally * indicative of as serious problem...) */ Template template = null; try { template = Velocity.GetTemplate(templateFile) ; } catch (ResourceNotFoundException) { System.Console.Out.WriteLine("Example1 : error : cannot find template " + templateFile); } catch (ParseErrorException pee) { System.Console.Out.WriteLine("Example1 : Syntax error in template " + templateFile + ":" + pee); } /* * Now have the template engine process your template using the * data placed into the context. Think of it as a 'merge' * of the template and the data to produce the output stream. */ if (template != null) { template.Merge(context, System.Console.Out); } } catch (System.Exception e) { System.Console.Out.WriteLine(e); } }
public static StringWriter GetFileText(string path, Hashtable ht) { if (String.IsNullOrEmpty(path)) { throw new ArgumentNullException("Argument Excception!"); } try { string tmpPath = path.Substring(0, path.LastIndexOf(@"\")); string filePath = path.Substring(path.LastIndexOf(@"\") + 1); VelocityEngine velocity = new VelocityEngine(); ExtendedProperties props = new ExtendedProperties(); props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file"); props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, tmpPath); props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, true); props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8"); props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8"); velocity.Init(props); Template temp = velocity.GetTemplate(filePath); IContext context = new VelocityContext(); foreach (string key in ht.Keys) { context.Put(key, ht[key]); } StringWriter writer = new StringWriter(); temp.Merge(context, writer); return(writer); } catch (Exception ex) { throw ex; } }