private bool RenderComponentView(InternalContextAdapter context, TextWriter writer, NVelocityViewContextAdapter contextAdapter) { foreach (DictionaryEntry entry in contextAdapter.ContextVars) { context.Put(entry.Key.ToString(), entry.Value); } try { String viewToRender = contextAdapter.ViewToRender; viewToRender = String.Format("{0}.vm", viewToRender); CheckTemplateStack(context); String encoding = SetUpEncoding(context); Template template = GetTemplate(viewToRender, encoding); return(RenderView(context, viewToRender, template, writer)); } finally { foreach (DictionaryEntry entry in contextAdapter.ContextVars) { context.Remove(entry.Key); } } }
public void TestJuxtaposePage() { SiteInfo site = new SiteInfo(); site.Copyright = "©2014 - 2015"; site.Description = ""; site.Host = "localhost"; site.KeyWords = ""; site.Logo = ""; site.Name = "xxx"; site.SiteDirectory = ""; site.Theme = "Blue"; site.ThemeDirectory = "theme"; site.Title = "jntemplate测试页"; site.Url = string.Concat("http://localhost"); if (!string.IsNullOrEmpty(site.SiteDirectory) && site.SiteDirectory != "/") { site.Url += "/" + site.SiteDirectory; } site.ThemeUrl = string.Concat(site.Url, "/", site.ThemeDirectory, "/", site.Theme); string basePath = new System.IO.DirectoryInfo(System.Environment.CurrentDirectory).Parent.Parent.FullName; string path = basePath + "\\templets\\nv"; NVelocity.Context.IContext ctx = new NVelocity.VelocityContext(); ctx.Put("func", new TemplateMethod()); ctx.Put("Site", site); NVelocity.App.VelocityEngine velocity = new NVelocity.App.VelocityEngine(); Commons.Collections.ExtendedProperties props = new Commons.Collections.ExtendedProperties(); props.AddProperty(NVelocity.Runtime.RuntimeConstants.RESOURCE_LOADER, "file"); props.AddProperty(NVelocity.Runtime.RuntimeConstants.FILE_RESOURCE_LOADER_PATH, path); props.AddProperty(NVelocity.Runtime.RuntimeConstants.INPUT_ENCODING, "utf-8"); props.AddProperty(NVelocity.Runtime.RuntimeConstants.OUTPUT_ENCODING, "utf-8"); velocity.Init(props); NVelocity.Template t = velocity.GetTemplate("questionlist.html"); string result; using (System.IO.StringWriter write = new StringWriter()) { t.Merge(ctx, write); result = write.ToString(); } //可直接查看项目录下的html/nv.html 文件效果 System.IO.File.WriteAllText(basePath + "\\html\\nv.html", result); }
/// <summary> /// merges a template and puts the rendered stream into the writer /// </summary> /// <param name="templateName">name of template to be used in merge /// </param> /// <param name="encoding">encoding used in template /// </param> /// <param name="context"> filled context to be used in merge /// </param> /// <param name="writer"> writer to write template into /// </param> /// <returns>true if successful, false otherwise. Errors /// logged to velocity log /// @since Velocity v1.1 /// </returns> public virtual bool MergeTemplate(System.String templateName, System.String encoding, IContext context, TextWriter writer) { Template template = ri.getTemplate(templateName, encoding) ; if (template == null) { ri.error("Velocity.parseTemplate() failed loading template '" + templateName + "'"); return(false); } else { template.Merge(context, writer); return(true); } }
public static Resource getResource(System.String resourceName, int resourceType) { Resource resource = null; switch (resourceType) { case NVelocity.Runtime.Resource.ResourceManager_Fields.RESOURCE_TEMPLATE: resource = new Template(); break; case NVelocity.Runtime.Resource.ResourceManager_Fields.RESOURCE_CONTENT: resource = new ContentResource(); break; } return resource; }
public static Resource getResource(System.String resourceName, int resourceType) { Resource resource = null; switch (resourceType) { case NVelocity.Runtime.Resource.ResourceManager_Fields.RESOURCE_TEMPLATE: resource = new Template(); break; case NVelocity.Runtime.Resource.ResourceManager_Fields.RESOURCE_CONTENT: resource = new ContentResource(); break; } return(resource); }
public void Process(String templateFile) { // Velocity 初始化. // 从配置文件读取配置信息. Velocity.Init("nvelocity.properties"); // 创建 Velocity Context VelocityContext context = new VelocityContext(); // 将列表的数据, 以 list 作为名称,放入 context. context.Put("list", Names); // 模版. 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); } // 处理模版信息. if (template != null) { template.Merge(context, System.Console.Out); } }
private bool RenderView(InternalContextAdapter context, String viewToRender, Template template, TextWriter writer) { try { context.PushCurrentTemplateName(viewToRender); ((SimpleNode)template.Data).render(context, writer); } catch (Exception e) { if (e is MethodInvocationException) { throw; } return(false); } finally { context.PopCurrentTemplateName(); } return(true); }
private bool RenderView(IInternalContextAdapter context, String viewToRender, Template template, TextWriter writer) { try { context.PushCurrentTemplateName(viewToRender); ((SimpleNode) template.Data).Render(context, writer); } catch(Exception e) { if (e is MethodInvocationException) { throw; } return false; } finally { context.PopCurrentTemplateName(); } return true; }
private void BuildOneFile(string className) { Type modelType = allTypeList.FirstOrDefault(p => p.FullName == className); if (modelType == null) { return; } //// 取得对象的所有属性. //PropertyInfo[] propArray = modelType.GetProperties(); //foreach (PropertyInfo prop in propArray) //{ // Console.WriteLine("属性名{0}, CanRead={1}, CanWrite={2}, 数据类型={3}", // prop.Name, prop.CanRead, prop.CanWrite, prop.PropertyType.Name); // Console.WriteLine("是否是抽象类{0}, 是否是类{1}", prop.PropertyType.IsAbstract, prop.PropertyType.IsClass); // Console.WriteLine("是否是数组{0}, 是否是枚举{1}", prop.PropertyType.IsArray, prop.PropertyType.IsEnum); // foreach (var attr in prop.GetCustomAttributes(true)) // { // Console.WriteLine("定义在属性上面的自定义特性: {0}", attr); // if (attr is System.ComponentModel.DataAnnotations.DisplayAttribute) // { // System.ComponentModel.DataAnnotations.DisplayAttribute displayAttr = attr as System.ComponentModel.DataAnnotations.DisplayAttribute; // Console.WriteLine("属性显示的标题:{0}", displayAttr.Name); // } // } // Console.WriteLine(); //} //var keyInfo = modelType.GetKeyInfo(); //Console.WriteLine("keyInfo = {0}", keyInfo); // Velocity 初始化. // 从配置文件读取配置信息. Velocity.Init("nvelocity.properties"); // 创建 Velocity Context VelocityContext context = new VelocityContext(); // 将数据, 以 Model 作为名称,放入 context. context.Put("Model", modelType); // 模版. Template template = null; string templateFile = this.cboTemplate.Text; // 尝试加载模版文件. try { template = Velocity.GetTemplate(templateFile, "utf-8"); } catch (ResourceNotFoundException) { MyMessage.Fail(String.Format("未能找到模板文件:{0}", templateFile)); } catch (ParseErrorException pee) { MyMessage.Fail(String.Format("解析模板文件 {0} 发生了异常!\n{1}", templateFile, pee)); } // 输出文件名, 去掉最后的 .vm string outputFileName = templateFile.Substring(0, templateFile.Length - 3); // 移除 template 目录. outputFileName = outputFileName.Replace("template\\", ""); // # 替换为类名. outputFileName = outputFileName.Replace("#", modelType.Name); try { // 处理模版信息. if (template != null) { string fileName = String.Format("{0}\\{1}", this.txtOutputPath.Text, outputFileName); using (StreamWriter sw = new StreamWriter(fileName, false, Encoding.UTF8)) { template.Merge(context, sw); } } } catch (Exception ex) { MyMessage.Fail(String.Format("根据模板文件 {0} 生成文档的过程中,发生了异常!\n{1}", templateFile, ex)); } }
/// <summary> Return name of this directive. /// </summary> /// <summary> Return type of this directive. /// </summary> /// <summary> iterates through the argument list and renders every /// argument that is appropriate. Any non appropriate /// arguments are logged, but render() continues. /// </summary> public override bool render(InternalContextAdapter context, System.IO.TextWriter writer, Node node) { /* * did we get an argument? */ if (node.jjtGetChild(0) == null) { rsvc.error("#parse() error : null argument"); return(false); } /* * does it have a value? If you have a null reference, then no. */ System.Object value_Renamed = node.jjtGetChild(0).value_Renamed(context); if (value_Renamed == null) { rsvc.error("#parse() error : null argument"); return(false); } /* * get the path */ //UPGRADE_TODO: The equivalent in .NET for method 'java.Object.toString' may return a different value. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1043"' System.String arg = value_Renamed.ToString(); /* * see if we have exceeded the configured depth. * If it isn't configured, put a stop at 20 just in case. */ System.Object[] templateStack = context.TemplateNameStack; if (templateStack.Length >= rsvc.getInt(NVelocity.Runtime.RuntimeConstants_Fields.PARSE_DIRECTIVE_MAXDEPTH, 20)) { System.Text.StringBuilder path = new System.Text.StringBuilder(); for (int i = 0; i < templateStack.Length; ++i) { path.Append(" > " + templateStack[i]); } rsvc.error("Max recursion depth reached (" + templateStack.Length + ")" + " File stack:" + path); return(false); } Resource current = context.CurrentResource; /* * get the resource, and assume that we use the encoding of the current template * the 'current resource' can be null if we are processing a stream.... */ System.String encoding = null; if (current != null) { encoding = current.Encoding; } else { encoding = (System.String)rsvc.getProperty(NVelocity.Runtime.RuntimeConstants_Fields.INPUT_ENCODING); } /* * now use the Runtime resource loader to get the template */ Template t = null; try { t = rsvc.getTemplate(arg, encoding); } catch (ResourceNotFoundException rnfe) { /* * the arg wasn't found. Note it and throw */ rsvc.error("#parse(): cannot find template '" + arg + "', called from template " + context.CurrentTemplateName + " at (" + Line + ", " + Column + ")"); throw rnfe; } catch (ParseErrorException pee) { /* * the arg was found, but didn't parse - syntax error * note it and throw */ rsvc.error("#parse(): syntax error in #parse()-ed template '" + arg + "', called from template " + context.CurrentTemplateName + " at (" + Line + ", " + Column + ")"); throw pee; } catch (System.Exception e) { rsvc.error("#parse() : arg = " + arg + ". Exception : " + e); return(false); } /* * and render it */ try { context.PushCurrentTemplateName(arg); ((SimpleNode)t.Data).render(context, writer); } catch (System.Exception e) { /* * if it's a MIE, it came from the render.... throw it... */ if (e is MethodInvocationException) { throw (MethodInvocationException)e; } rsvc.error("Exception rendering #parse( " + arg + " ) : " + e); return(false); } finally { context.PopCurrentTemplateName(); } return(true); }
/// <summary> actual factory : creates a Directive that will /// behave correctly wrt getting the framework to /// dig out the correct # of args /// </summary> public virtual Directive.Directive getVelocimacro(System.String vmName, System.String sourceTemplate) { VelocimacroProxy vp = null; lock (this) { /* * don't ask - do */ vp = vmManager.get(vmName, sourceTemplate); /* * if this exists, and autoload is on, we need to check * where this VM came from */ if (vp != null && Autoload) { /* * see if this VM came from a library. Need to pass sourceTemplate * in the event namespaces are set, as it could be masked by local */ System.String lib = vmManager.getLibraryName(vmName, sourceTemplate); if (lib != null) { try { /* * get the template from our map */ Twonk tw = (Twonk)libModMap[lib]; if (tw != null) { Template template = tw.template; /* * now, compare the last modified time of the resource * with the last modified time of the template * if the file has changed, then reload. Otherwise, we should * be ok. */ long tt = tw.modificationTime; long ft = template.ResourceLoader.getLastModified(template) ; if (ft > tt) { logVMMessageInfo("Velocimacro : autoload reload for VMs from " + "VM library template : " + lib); /* * when there are VMs in a library that invoke each other, * there are calls into getVelocimacro() from the init() * process of the VM directive. To stop the infinite loop * we save the current time reported by the resource loader * and then be honest when the reload is complete */ tw.modificationTime = ft; template = rsvc.getTemplate(lib) ; /* * and now we be honest */ tw.template = template; tw.modificationTime = template.LastModified; /* * note that we don't need to put this twonk back * into the map, as we can just use the same reference * and this block is synchronized */ } } } catch (System.Exception e) { logVMMessageInfo("Velocimacro : error using VM " + "library template " + lib + " : " + e); } /* * and get again */ vp = vmManager.get(vmName, sourceTemplate); } } } return(vp); }
/// <summary> initialize the factory - setup all permissions /// load all global libraries. /// </summary> public virtual void initVelocimacro() { /* * maybe I'm just paranoid... */ lock (this) { /* * allow replacements while we add the libraries, if exist */ ReplacementPermission = true; Blather = true; logVMMessageInfo("Velocimacro : initialization starting."); /* * add all library macros to the global namespace */ vmManager.NamespaceUsage = false; /* * now, if there is a global or local libraries specified, use them. * All we have to do is get the template. The template will be parsed; * VM's are added during the parse phase */ System.Object libfiles = rsvc.getProperty(NVelocity.Runtime.RuntimeConstants_Fields.VM_LIBRARY); if (libfiles != null) { if (libfiles is System.Collections.ArrayList) { macroLibVec = (System.Collections.ArrayList)libfiles; } else if (libfiles is System.String) { macroLibVec = new System.Collections.ArrayList(); macroLibVec.Add(libfiles); } for (int i = 0; i < macroLibVec.Count; i++) { System.String lib = (System.String)macroLibVec[i]; /* * only if it's a non-empty string do we bother */ if (lib != null && !lib.Equals("")) { /* * let the VMManager know that the following is coming * from libraries - need to know for auto-load */ vmManager.RegisterFromLib = true; logVMMessageInfo("Velocimacro : adding VMs from " + "VM library template : " + lib); try { Template template = rsvc.getTemplate(lib); /* * save the template. This depends on the assumption * that the Template object won't change - currently * this is how the Resource manager works */ Twonk twonk = new Twonk(this); twonk.template = template; twonk.modificationTime = template.LastModified; libModMap[lib] = twonk; } catch (System.Exception e) { logVMMessageInfo("Velocimacro : error using VM " + "library template " + lib + " : " + e); } logVMMessageInfo("Velocimacro : VM library template " + "macro registration complete."); vmManager.RegisterFromLib = false; } } } /* * now, the permissions */ /* * allowinline : anything after this will be an inline macro, I think * there is the question if a #include is an inline, and I think so * * default = true */ AddMacroPermission = true; if (!rsvc.getBoolean(NVelocity.Runtime.RuntimeConstants_Fields.VM_PERM_ALLOW_INLINE, true)) { AddMacroPermission = false; logVMMessageInfo("Velocimacro : allowInline = false : VMs can not " + "be defined inline in templates"); } else { logVMMessageInfo("Velocimacro : allowInline = true : VMs can be " + "defined inline in templates"); } /* * allowInlineToReplaceGlobal : allows an inline VM , if allowed at all, * to replace an existing global VM * * default = false */ ReplacementPermission = false; if (rsvc.getBoolean(NVelocity.Runtime.RuntimeConstants_Fields.VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL, false)) { ReplacementPermission = true; logVMMessageInfo("Velocimacro : allowInlineToOverride = true : VMs " + "defined inline may replace previous VM definitions"); } else { logVMMessageInfo("Velocimacro : allowInlineToOverride = false : VMs " + "defined inline may NOT replace previous VM definitions"); } /* * now turn on namespace handling as far as permissions allow in the * manager, and also set it here for gating purposes */ vmManager.NamespaceUsage = true; /* * template-local inline VM mode : default is off */ TemplateLocalInline = rsvc.getBoolean(NVelocity.Runtime.RuntimeConstants_Fields.VM_PERM_INLINE_LOCAL, false); if (TemplateLocalInline) { logVMMessageInfo("Velocimacro : allowInlineLocal = true : VMs " + "defined inline will be local to their defining template only."); } else { logVMMessageInfo("Velocimacro : allowInlineLocal = false : VMs " + "defined inline will be global in scope if allowed."); } vmManager.TemplateLocalInlineVM = TemplateLocalInline; /* * general message switch. default is on */ Blather = rsvc.getBoolean(NVelocity.Runtime.RuntimeConstants_Fields.VM_MESSAGES_ON, true); if (Blather) { logVMMessageInfo("Velocimacro : messages on : VM system " + "will output logging messages"); } else { logVMMessageInfo("Velocimacro : messages off : VM system will be quiet"); } /* * autoload VM libraries */ Autoload = rsvc.getBoolean(NVelocity.Runtime.RuntimeConstants_Fields.VM_LIBRARY_AUTORELOAD, false); if (Autoload) { logVMMessageInfo("Velocimacro : autoload on : VM system " + "will automatically reload global library macros"); } else { logVMMessageInfo("Velocimacro : autoload off : VM system " + "will not automatically reload global library macros"); } rsvc.info("Velocimacro : initialization complete."); } return; }
private void BuildAllFile(List <Chapter> cList) { List <Chapter> chapterList = new List <Chapter>(); foreach (var c in cList) { Chapter myChapter = new Chapter(); myChapter.BookCode = c.BookCode; myChapter.ChapterCode = c.ChapterCode; myChapter.ChapterName = c.ChapterName; // 取得行列表. myChapter.Lines = lineService.GetChapterLineList(c.ChapterCode); chapterList.Add(myChapter); } // Velocity 初始化. // 从配置文件读取配置信息. Velocity.Init("nvelocity.properties"); // 创建 Velocity Context VelocityContext context = new VelocityContext(); // 将列表的数据, 以 ChapterList 作为名称,放入 context. context.Put("ChapterList", chapterList); // 模版. Template template = null; string templateFile = this.cboTemplate.Text; // 尝试加载模版文件. try { template = Velocity.GetTemplate(templateFile); } catch (ResourceNotFoundException) { MyMessage.Fail(String.Format("未能找到模板文件:{0}", templateFile)); } catch (ParseErrorException pee) { MyMessage.Fail(String.Format("解析模板文件 {0} 发生了异常!\n{1}", templateFile, pee)); } try { // 处理模版信息. if (template != null) { string fileName = String.Format("{0}\\{1}.{2}", this.txtOutputPath.Text, this.cboBooks.SelectedValue, this.cboTemplate.SelectedFileType); using (StreamWriter sw = new StreamWriter(fileName, false, Encoding.UTF8)) { template.Merge(context, sw); } } } catch (Exception ex) { MyMessage.Fail(String.Format("根据模板文件 {0} 生成文档的过程中,发生了异常!\n{1}", templateFile, ex)); } }