public void CacheProblems() { VelocityContext context = new VelocityContext(); context.Put("AjaxHelper2", new AjaxHelper2()); context.Put("DictHelper", new DictHelper()); Template template = velocityEngine.GetTemplate( GetFileName(null, "dicthelper", TemplateTest.TMPL_FILE_EXT)); StringWriter writer = new StringWriter(); template.Merge(context, writer); System.Console.WriteLine(writer.GetStringBuilder().ToString()); writer = new StringWriter(); template.Merge(context, writer); System.Console.WriteLine(writer.GetStringBuilder().ToString()); writer = new StringWriter(); template.Merge(context, writer); System.Console.WriteLine(writer.GetStringBuilder().ToString()); }
/// <summary> /// 写入文件 /// </summary> /// <param name="writeFilePath">文件路径</param> /// <param name="vmName">VM模板全名称</param> /// <param name="model">需要实体</param> /// <param name="isWrite">是否写入文件默认为写入</param> /// <returns>写入的字符串</returns> protected virtual string CreateFile(string writeFilePath, string vmName, object model, bool isWrite = true) { // 获取模板并且设置参数 Template template = VelocityEngine.GetTemplate(vmName); VelocityContext context = new VelocityContext(); context.Put("people", "华威"); context.Put("model", model); StringWriter writer = new StringWriter(); template.Merge(context, writer); var result = writer.GetStringBuilder().ToString(); //2. 内容写入到指定文件 if (isWrite) { // 文件如果不存在 if (!File.Exists(writeFilePath)) { File.WriteAllText(writeFilePath, result); } else if (APP.Configuration.IsCover) // 同意重写才会重写 { File.WriteAllText(writeFilePath, result); } } return(result); }
/// <summary> /// 显示模板 /// </summary> /// <param name="templatFileName">模板文件名</param> public void Display(string templatFileName) { //从文件中读取模板 Template template = new Template(); try { template = velocity.GetTemplate(templatFileName); } catch (Exception ex) { } //合并模板 StringWriter writer = new StringWriter(); template.Merge(context, writer); //输出 // HttpContext.Current.Response.Clear(); // HttpContext.Current.Response.ClearContent(); HttpContext.Current.Response.Write(writer.ToString()); if (JavaScript.Length > 0) { HttpContext.Current.Response.Write("<script" + ">" + JavaScript + "</" + "script>"); } HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); }
protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) { Template viewTemplate = _engine.GetTemplate(viewPath); Template masterTemplate = _engine.GetTemplate(masterPath); NVelocityView view = new NVelocityView(controllerContext, viewTemplate, masterTemplate); return(view); }
/// <summary> /// 显示模板 /// </summary> /// <param name="templatFileName">模板文件名</param> public void Display(string templatFileName) { Template template = velocity.GetTemplate(templatFileName); StringWriter writer = new StringWriter(); template.Merge(context, writer); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Write(writer.ToString()); HttpContext.Current.Response.End(); }
/// <summary> /// 保存生成的文件 /// </summary> /// <param name="inputFileName">模板名称</param> /// <param name="outPutFilePath">生成文件完全限定名(包括路径)</param> public void Save(string inputFileName, string outPutFilePath) { Template template = velocity.GetTemplate(inputFileName); using (StreamWriter sw = new StreamWriter(outPutFilePath, false, Encoding.UTF8)) { template.Merge(context, sw); sw.Flush(); sw.Close(); } }
/// <summary> /// Returns <c>true</c> only if the /// specified template exists and can be used /// </summary> /// <param name="templateName"></param> /// <returns></returns> public bool HasTemplate(String templateName) { try { vengine.GetTemplate(templateName); return(true); } catch (Exception) { return(false); } }
/// <summary> /// Display /// </summary> /// <param name="path">path</param> public void Display(string path) { //加载模板 Template vm = ve.GetTemplate(path); //写入 using (StringWriter sw = new StringWriter()) { vm.Merge(vc, sw); //输出 HttpContext.Current.Response.Write(sw.ToString()); } }
public override void Process(IRailsEngineContext context, Controller controller, String viewName) { IContext ctx = CreateContext(context, controller); AdjustContentType(context); Template template = null; bool hasLayout = controller.LayoutName != null; TextWriter writer; if (hasLayout) { writer = new StringWriter(); //Because we are rendering within a layout we need to catch it first } else { writer = context.Response.Output; //No layout so render direct to the output } String view = ResolveTemplateName(viewName); try { template = velocity.GetTemplate(view); PreSendView(controller, template); template.Merge(ctx, writer); PostSendView(controller, template); } catch (Exception) { if (hasLayout) { // Restore original writer writer = context.Response.Output; } throw; } if (hasLayout) { String contents = (writer as StringWriter).GetStringBuilder().ToString(); ProcessLayout(contents, controller, ctx, context); } }
/// <summary> /// Pendent. /// </summary> /// <param name="output">The output.</param> /// <param name="context">The context.</param> /// <param name="controller">The controller.</param> /// <param name="controllerContext">The controller context.</param> /// <param name="viewName">Name of the view.</param> public override void Process(String viewName, TextWriter output, IEngineContext context, IController controller, IControllerContext controllerContext) { var ctx = CreateContext(context, controller, controllerContext); try { AdjustContentType(context); var hasLayout = controllerContext.LayoutNames != null && controllerContext.LayoutNames.Length != 0; TextWriter writer; if (hasLayout) { // Because we are rendering within a layout we need to catch it first writer = new StringWriter(); } else { // No layout so render direct to the output writer = output; } var view = ResolveTemplateName(viewName); var template = velocity.GetTemplate(view); PreSendView(controller, template); BeforeMerge(velocity, template, ctx); template.Merge(ctx, writer); PostSendView(controller, template); if (hasLayout) { ProcessLayoutRecursively((StringWriter)writer, context, controller, controllerContext, ctx, output); } } catch (Exception ex) { if (Logger.IsErrorEnabled) { Logger.Error("Could not render view", ex); } throw; } }
/// <summary> /// 显示模板 /// </summary> /// <param name="httpcontext"></param> /// <param name="templateFileName"></param> public void Display(HttpContext httpcontext, string templateFileName) { //从文件中读取模板 Template template = velocity.GetTemplate(templateFileName); //合并模板 StringWriter writer = new StringWriter(); template.Merge(context, writer); //输出 httpcontext.Response.Clear(); httpcontext.Response.Write(writer.ToString()); httpcontext.Response.Flush(); httpcontext.ApplicationInstance.CompleteRequest(); }
/// <summary> /// 显示模板 /// </summary> /// <param name="tmplFileName">模板文件名</param> public void Display(string tmplFileName) { //从文件中读取模板 Template template = velocity.GetTemplate(tmplFileName); //合并模板 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(); }
/// <summary> /// 生成按主键查询SQL /// </summary> public void GenerateFetchStatement(List <Table> tables) { if (tables == null || tables.Count == 0) { throw new Exception("no job!"); } var vltContext = new VelocityContext(); vltContext.Put("Tables", tables); Template vltTemplate = vltEngine.GetTemplate("fetch.vm"); var vltWriter = new System.IO.StringWriter(); vltTemplate.Merge(vltContext, vltWriter); File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "_f_" + tables.First().DatabaseRealName.ToLower() + ".xml", vltWriter.GetStringBuilder().ToString()); }
/// <summary> /// 初始化模板引擎 /// </summary> public void Init() { try { VelocityEngine templateEngine = new VelocityEngine(); templateEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); templateEngine.SetProperty(RuntimeConstants.INPUT_ENCODING, "utf-8"); templateEngine.SetProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8"); //如果设置了FILE_RESOURCE_LOADER_PATH属性,那么模板文件的基础路径就是基于这个设置的目录, //否则默认当前运行目录 templateEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, UnityEngine.Application.dataPath); templateEngine.Init(); template = templateEngine.GetTemplate(FilePathManager.Instance.GetTemplateFilePath()); } catch (NVelocity.Exception.ResourceNotFoundException re) { string error = string.Format("Cannot find template " + ""); Console.WriteLine(error); throw new Exception(error, re); } catch (NVelocity.Exception.ParseErrorException pee) { string error = string.Format("Syntax error in template " + "" + ":" + pee.StackTrace); Console.WriteLine(error); throw new Exception(error, pee); } }
public StringWriter CreateControlFile() { VelocityEngine velocity = new VelocityEngine(); ExtendedProperties props = new ExtendedProperties(); props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "assembly"); props.AddProperty("assembly.resource.loader.class", "NVelocity.Runtime.Resource.Loader.AssemblyResourceLoader, NVelocity"); props.AddProperty("assembly.resource.loader.assembly", GetType().Assembly.GetName().Name); velocity.Init(props); // todo how do i get template as stream. check hwb code. // Set up the required velocity data types and parameters Template controlTemplate = velocity.GetTemplate("CSIRO.Metaheuristics.UseCases.PEST.Resources.ControlFile.vm"); StringWriter writer = new StringWriter(); VelocityContext controlContext = new VelocityContext(); string val = this.RestartFile.ToString(); controlContext.Put("restartFile", this.RestartFile.ToString()); controlContext.Put("ControlData", this); controlTemplate.Merge(controlContext, writer); return(writer); }
/// <summary>合并</summary> /// <param name="context">上下文环境</param> /// <param name="templatePath">模板相对路径</param> /// <returns></returns> public string Merge(VelocityContext context, string templatePath) { try { if (engine.TemplateExists(templatePath)) { Template template = engine.GetTemplate(templatePath); return(Merge(context, template)); } else { return("Can't find \"" + templatePath + "\"."); } } catch { // 发生内部错误, 重启引擎. instance = null; engine = null; return(string.Empty); } }
public MailMessage Parse(IMailTemplate template, object model) { var context = new VelocityContext(); var args = GetArgs(model); if (!args.ContainsKey("helper")) { context.Put("helper", new TemplateHelper()); } foreach (var arg in args) { context.Put(arg.Key, arg.Value); } var result = ""; using (var sw = new StringWriter()) { var content = template.ToStringContent(); NVelocityDirectResourceLoader.CurrentEncoding = template.Encoding; var tmp = engine.GetTemplate(content, template.Encoding.EncodingName); tmp.Merge(context, sw); result = sw.ToString(); } return(XmlMailSerializer.Deserialize(result)); }
private void button1_Click(object sender, EventArgs e) { VelocityEngine velocityEngine = new VelocityEngine(); ExtendedProperties props = new ExtendedProperties(); props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file"); //props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, HttpContext.Current.Server.MapPath(templatDir); props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, @""); //props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Path.GetDirectoryName(HttpContext.Current.Request.PhysicalPath)); props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8"); props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8"); //模板的缓存设置 props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, true); //是否缓存 props.AddProperty("file.resource.loader.modificationCheckInterval", (Int64)30); //缓存时间(秒) velocityEngine.Init(props); //为模板变量赋值 VelocityContext context = new VelocityContext(); context.Put("Time", "20170613"); context.Put("Title", "模板生成"); context.Put("Body", "内容"); // Template template = velocityEngine.GetTemplate(@"D:\ProgrammingFolder\C#\NVelocityDemo\NVelocityDemo\bin\Debug\Template"); //从文件中读取模板 Template template = velocityEngine.GetTemplate(@"C:\Users\Macroinf—PC135\source\repos\CodeGen\CodeGen\bin\Debug\Value.vm"); //合并模板 using (StreamWriter writer = new StreamWriter(@"C:\Users\Macroinf—PC135\source\repos\CodeGen\CodeGen\bin\Debug\123.cs", false)) { template.Merge(context, writer); } }
/// <summary> /// 缓存模板对象 /// </summary> /// <param name="folder"></param> /// <param name="fileName"></param> /// <returns></returns> public NVelocity.Template GetTemplate(string templateFile) { CacheProvider cache = CacheProvider.GetCacheService(); templatePath = templatePath.Replace("\\", "").Replace(":", "").Replace("_", ""); // string xpath = String.Format("/Template/{0}/{1}", templatePath, templateFile); string xpath = String.Format("/Template/{0}", templateFile); NVelocity.Template template = (NVelocity.Template)cache.RetrieveObject(xpath); if (template == null) { //VelocityEngine velocity = new VelocityEngine(); //ExtendedProperties props = new ExtendedProperties(); //props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file"); //props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templatePath); //props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8"); //props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8"); //velocity.Init(props); template = velocity.GetTemplate(templateFile); if (template == null) { throw new NullReferenceException("模板目录不存在。"); } cache.AddObject(xpath, template, templateCacheTime); } return(template); }
/// <summary> Returns a template, based on encoding and path. /// * /// </summary> /// <param name="templateName"> name of the template /// </param> /// <param name="encoding"> template encoding /// /// </param> public virtual Template getTemplate(System.String templateName, System.String encoding) { Template template; if (encoding == null || encoding.Length == 0 || encoding.Equals("8859-1") || encoding.Equals("8859_1")) { template = ve.GetTemplate(templateName) ; } else { template = ve.GetTemplate(templateName, encoding) ; } return(template); }
public void Test() { var velocityEngine = new VelocityEngine(); ExtendedProperties extendedProperties = new ExtendedProperties(); extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateTest.FILE_RESOURCE_LOADER_PATH); velocityEngine.Init(extendedProperties); VelocityContext context = new VelocityContext(); context.Put("yada", "line"); Template template = velocityEngine.GetTemplate( GetFileName(null, "nv37", TemplateTest.TMPL_FILE_EXT)); StringWriter writer = new StringWriter(); #pragma warning disable 612,618 velocityEngine.MergeTemplate("nv37.vm", context, writer); #pragma warning restore 612,618 //template.Merge(context, writer); Console.WriteLine(writer); }
public string Merge(string templateString, IDictionary <string, object> parameters) { if (templateString == null) { throw new ArgumentNullException("templateString"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (!parameters.ContainsKey("now")) { parameters.Add("now", DateTime.Now); } if (!parameters.ContainsKey("formatter")) { parameters.Add("formatter", new NVelocityTemplateEngineFormatter()); } var template = _velocity.GetTemplate(templateString); var context = new VelocityContext(); parameters.ToList() .ForEach(item => context.Put(item.Key, item.Value)); using (var writer = new StringWriter()) { template.Merge(context, writer); return(writer.ToString()); } }
protected void Page_Load(object sender, EventArgs e) { this.ltlUserName.Text = CookieUtilities.GetCookieValue("username"); using (var context = new MemberContext()) { VelocityEngine ve = new VelocityEngine(); ve.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); ve.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Server.MapPath("~/html_template")); ve.Init(); VelocityContext vContext = new VelocityContext(); var entities = context.RoleFunctions.Where(a => a.RoleId == RoleId && a.ParentID.EndsWith("_0")).Select(a => a).ToList(); List <Item> items = new List <Item>(); foreach (var entity in entities) { var item = new Item(); item.Name = entity.Name; item.IconClass = entity.IconClass; item.Url = entity.Url; item.Items = context.RoleFunctions.Where(a => a.RoleId == RoleId && a.ParentID.StartsWith(entity.ParentID.Substring(0, 2))).Where(a => a.Name != entity.Name).Select(a => new Item { Name = a.Name, Url = a.Url }).ToList <Item>(); items.Add(item); } vContext.Put("items", items); Template template = ve.GetTemplate("menu.html"); StringWriter writer = new StringWriter(); template.Merge(vContext, writer); MenuString = writer.GetStringBuilder().ToString(); } }
/// <summary> /// 初始化模板引擎 /// </summary> protected virtual void InitTemplateEngine() { try { //Velocity.Init(NVELOCITY_PROPERTY); VelocityEngine templateEngine = new VelocityEngine(); templateEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); templateEngine.SetProperty(RuntimeConstants.INPUT_ENCODING, "utf-8"); templateEngine.SetProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8"); //如果设置了FILE_RESOURCE_LOADER_PATH属性,那么模板文件的基础路径就是基于这个设置的目录,否则默认当前运行目录 templateEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, AppDomain.CurrentDomain.BaseDirectory); templateEngine.Init(); template = templateEngine.GetTemplate(templateFile); } catch (ResourceNotFoundException re) { string error = string.Format("Cannot find template " + templateFile); LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, re, typeof(NVelocityHelper)); throw new Exception(error, re); } catch (ParseErrorException pee) { string error = string.Format("Syntax error in template " + templateFile + ":" + pee.StackTrace); LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, pee, typeof(NVelocityHelper)); throw new Exception(error, pee); } }
public void LineComponent1() { VelocityContext context = new VelocityContext(); Template template = velocityEngine.GetTemplate( GetFileName(null, "componentusage1", TemplateTest.TMPL_FILE_EXT)); StringWriter writer = new StringWriter(); template.Merge(context, writer); System.Console.WriteLine(writer.GetStringBuilder().ToString()); writer = new StringWriter(); template.Merge(context, writer); System.Console.WriteLine(writer.GetStringBuilder().ToString()); writer = new StringWriter(); template.Merge(context, writer); System.Console.WriteLine(writer.GetStringBuilder().ToString()); }
public void Apply(IEnumerable <ChangeScript> changeScripts) { string filename = string.Format(CultureInfo.InvariantCulture, "{0}_{1}.vm", this.syntax, this.GetTemplateQualifier()); var model = new Hashtable(); model.Add("scripts", changeScripts); model.Add("changeLogTableName", this.changeLogTableName); model.Add("delimiter", this.delimiter); model.Add("separator", this.delimiterType is RowDelimiter ? Environment.NewLine : string.Empty); try { ExtendedProperties props = new ExtendedProperties(); var assemblyName = this.GetType().Assembly.GetName().Name; ReplaceManagersWithDbDeployVersions(props, assemblyName); if (this.templateDirectory == null) { props.AddProperty("resource.loader", "assembly"); props.AddProperty("assembly.resource.loader.class", // See the ; there? It will be replaced by , in the resource loader factory // this is because if we add a property with a comma in the value, it will add *two* values to the property. // oh joy. typeof(DbDeployAssemblyResourceLoader).FullName + "; " + assemblyName); props.AddProperty("assembly.resource.loader.assembly", assemblyName); filename = "Net.Sf.Dbdeploy.Resources." + filename; } else { props.SetProperty("file.resource.loader.path", this.templateDirectory.FullName); } var templateEngine = new VelocityEngine(props); var context = new VelocityContext(model); Template template = templateEngine.GetTemplate(filename); template.Merge(context, this.writer); } catch (ResourceNotFoundException ex) { string locationMessage; if (templateDirectory == null) { locationMessage = ""; } else { locationMessage = " at " + templateDirectory.FullName; } throw new UsageException( "Could not find template named " + filename + locationMessage + Environment.NewLine + "Check that you have got the name of the database syntax correct.", ex); } }
/// <summary> /// 通过模板文件 生成文件 /// </summary> /// <param name="templatePath"></param> /// <param name="templateFileName"></param> /// <param name="outFilePath"></param> /// <param name="dictKv"></param> public static void WriteTemplateByFile(string templatePath, string templateFileName, string outFilePath, Dictionary <string, object> dictKv) { // 初始化模板引擎 VelocityEngine ve = new VelocityEngine(); //可选值:"class"--从classpath中读取,"file"--从文件系统中读取 ve.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file"); //如果从文件系统中读取模板,那么属性值为org.apache.velocity.runtime.resource.loader.FileResourceLoader ve.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, @templatePath); ve.Init(); //模板内容 VelocityContext vlc = new VelocityContext(); foreach (string key in dictKv.Keys) { vlc.Put(key, dictKv[key]); } /* *指定引擎加载的模版 */ Template vtp = ve.GetTemplate(@templateFileName); StringWriter str = new StringWriter(); vtp.Merge(vlc, str); File.WriteAllText(@outFilePath, str.GetStringBuilder().ToString());//生成文件的路径可以自由选择 MessageBox.Show(str.GetStringBuilder().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 bool Run(TemplateData templateData) { VelocityContext context = new VelocityContext(); context.Put("tdo", templateData); try { string loaderPath = Path.GetDirectoryName(templateData.TemplateFileName); string templateFile = Path.GetFileName(templateData.TemplateFileName); velocityEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, loaderPath); velocityEngine.Init(); Template template = velocityEngine.GetTemplate(templateFile); using (StreamWriter StreamWriter = new StreamWriter(templateData.CodeFileName, false, Encoding.GetEncoding(templateData.Encoding))) { template.Merge(context, StreamWriter); } return(true); } catch (Exception ex) { logger.Error(String.Format("NVelocityAdapter:{0}", templateData.CodeFileName), ex); return(false); } }
public static Template GetTemplate(string tempPath) { //第一步:Creating a VelocityEngine也就是创建一个VelocityEngine的实例 VelocityEngine vltEngine = new VelocityEngine(); ExtendedProperties vltProps = new ExtendedProperties(); vltProps.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8"); vltProps.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8"); vltEngine.Init(vltProps); //第二步:Creating the Template加载模板文件 Template vltTemplate = new Template(); try { vltTemplate = vltEngine.GetTemplate(tempPath); } catch (Exception e) { Debug.Log(e.Message); return(null); } return(vltTemplate); }
public void Test() { var velocityEngine = new VelocityEngine(); ExtendedProperties extendedProperties = new ExtendedProperties(); extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateTest.FILE_RESOURCE_LOADER_PATH); velocityEngine.Init(extendedProperties); VelocityContext context = new VelocityContext(); context.Put("yada", "line"); Template template = velocityEngine.GetTemplate( GetFileName(null, "nv37", TemplateTest.TMPL_FILE_EXT)); StringWriter writer = new StringWriter(); #pragma warning disable 612,618 velocityEngine.MergeTemplate("nv37.vm", context, writer); #pragma warning restore 612,618 //template.Merge(context, writer); Console.WriteLine(writer); }
/// <summary> /// Render nVelocity template to HTML /// </summary> /// <param name="output">Output text writer</param> public override void Render(TextWriter output) { // .Replace(',', ';') нужен за внутренними надобнастями NVelocity // Внутри библиотеки символы меняются обратно. // Проблема связана с форматом представления массивов векторов и строк. String loader_class_name = typeof(CustomResourceLoader).AssemblyQualifiedName.Replace(',', ';'); VelocityEngine velocity = new VelocityEngine(); velocity.AddProperty(RuntimeConstants.RESOURCE_LOADER, "webcore"); velocity.AddProperty("webcore.resource.loader.class", loader_class_name); velocity.AddProperty("webcore.resource.loader.domain", DomainName); velocity.Init(); Template tpl = velocity.GetTemplate(ViewName); tpl.Merge(this.items, output); }
public void Test() { var velocityEngine = new VelocityEngine(); ExtendedProperties extendedProperties = new ExtendedProperties(); extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateTest.FILE_RESOURCE_LOADER_PATH); velocityEngine.Init(extendedProperties); VelocityContext context = new VelocityContext(); Template template = velocityEngine.GetTemplate( GetFileName(null, "nv09", TemplateTest.TMPL_FILE_EXT)); StringWriter writer = new StringWriter(); template.Merge(context, writer); }
public void Test_Example1() { String templateFile = "example1.vm"; try { /* * setup */ VelocityEngine velocityEngine = new VelocityEngine(); ExtendedProperties extendedProperties = new ExtendedProperties(); extendedProperties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, TemplateTest.FILE_RESOURCE_LOADER_PATH); velocityEngine.Init(extendedProperties); /* * 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", GetNames()); ExtendedProperties props = new ExtendedProperties(); props.Add("runtime.log", "nvelocity.log"); context.Put("props", props); /* * 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 = velocityEngine.GetTemplate(templateFile); } catch(ResourceNotFoundException resourceNotFoundException) { Console.Out.WriteLine("Example : error : cannot find template {0} : \n{1}", templateFile, resourceNotFoundException.Message); Assert.Fail(); } catch(ParseErrorException parseErrorException) { Console.Out.WriteLine("Example : Syntax error in template {0} : \n{1}", templateFile, parseErrorException); Assert.Fail(); } /* * 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. */ // using Console.Out will send it to the screen TextWriter writer = new StringWriter(); if (template != null) template.Merge(context, writer); /* * flush and cleanup */ writer.Flush(); writer.Close(); } catch(Exception ex) { Assert.Fail(ex.Message); } }