This class is used for controlling all template operations. This class uses a parser created by JavaCC to create an AST that is subsequently traversed by a Visitor. Template template = Velocity.getTemplate("test.wm"); IContext context = new VelocityContext(); context.Put("foo", "bar"); context.Put("customer", new Customer()); template.Merge(context, writer);
Inheritance: NVelocity.Runtime.Resource.Resource
示例#1
0
        /// <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);
        }
示例#2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NVelocityView"/> class.
 /// </summary>
 /// <param name="template">The template.</param>
 /// <param name="viewData">The view data.</param>
 /// <param name="engine">The engine.</param>
 public NVelocityView(Template template, ViewDataDictionary viewData, VelocityEngine engine)
 {
     _context = new VelocityContext();
     _template = template;
     _engine = engine;
     ViewData = viewData;
 }
示例#3
0
        /// <summary>
        /// 生成字符
        /// </summary>
        /// <param name="templatFileName">模板文件名</param>
        public string BuildString(string templateFile)
        {
            //从文件中读取模板
            // NVelocity.Template template = velocity.GetTemplate(templateFile);
            NVelocity.Template template = GetTemplate(templateFile);

            //合并模板
            StringWriter writer = new StringWriter();

            template.Merge(context, writer);
            return(writer.ToString());
        }
示例#4
0
 public static string TemplateMerge(string name, Hashtable table)
 {
     template = engine.GetTemplate(filePath+name);
     VelocityContext content = new VelocityContext();
     foreach (DictionaryEntry entry in table)
     {
         content.Put(entry.Key.ToString(), entry.Value);
     }
     StringWriter writer = new StringWriter();
     template.Merge(content, writer);
     return writer.GetStringBuilder().ToString();
 }
    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);
        }
    }
        private void GeneratePage(Template template, int pageIndex)
        {
            VelocityContext.Put("pageIndex", pageIndex);
            string reportPath = Helper.Paging.GetReportPath(pageIndex);
            var stringBuilder = new StringBuilder();

            using (var stringWriter = new StringWriter(stringBuilder))
            {
                template.Merge(VelocityContext, stringWriter);

                using (var fileWriter = new StreamWriter(ReportWriter.ReportContainer.OpenWrite(reportPath, ContentType, encoding)))
                {
                    fileWriter.Write(FormatHtmlHelper.Flatten(stringBuilder.ToString()));
                }
            }

            ReportWriter.AddReportDocumentPath(reportPath);
        }
        public static string ParseVelocity(string path, string name, IDictionary <string, object> parameters)
        {
            StringWriter       writer     = new StringWriter();
            ExtendedProperties properties = new ExtendedProperties();

            properties.AddProperty("resource.loader", "file");
            properties.AddProperty("file.resource.loader.path", path);
            VelocityEngine engine = new VelocityEngine();

            engine.Init(properties);
            IContext context = new VelocityContext();

            foreach (KeyValuePair <string, object> pair in parameters)
            {
                context.Put(pair.Key, pair.Value);
            }
            Template template = engine.GetTemplate(name);

            if (template != null)
            {
                template.Merge(context, writer);
            }
            return(writer.ToString());
        }
        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;
            }
        }
		protected virtual void BeforeMerge(VelocityEngine velocityEngine, Template template, IContext context)
		{
		}
		private bool RenderView(IInternalContextAdapter context,
		                        String viewToRender, Template template, TextWriter writer)
		{
			try
			{
				context.PushCurrentTemplateName(viewToRender);
				((SimpleNode) template.Data).Render(context, writer);
			}
			finally
			{
				context.PopCurrentTemplateName();
			}

			return true;
		}
示例#11
0
 public NVelocityView(Template viewTemplate, Template masterTemplate)
 {
     _viewTemplate = viewTemplate;
     _masterTemplate = masterTemplate;
 }
示例#12
0
        /// <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();
        }
示例#13
0
 public NVelocityView(Template template,IContext velocityContext)
 {
     _template = template;
     _velocityContext = velocityContext;
 }
示例#14
0
	/// <summary>
	/// merges the template with the context.  Only override this if you really, really
	/// really need to. (And don't call us with questions if it breaks :)
	/// </summary>
	/// <param name="template">template object returned by the handleRequest() method</param>
	/// <param name="ctx">context created by the CreateContext() method</param>
	/// <param name="response">TextWriter to write to (i.e. Response.Output)</param>
	protected virtual void MergeTemplate(Template template, IContext ctx, TextWriter response) {
	    template.Merge(ctx, response);
	}
示例#15
0
 public NVelocityView(ControllerContext controllerContext, Template viewTemplate, Template masterTemplate)
 {
     _controllerContext = controllerContext;
     _viewTemplate = viewTemplate;
     _masterTemplate = masterTemplate;
 }
        public override void Configure(DirectoryInfo workingDirectory, NameValueCollection props)
        {
            try
            {
                File.Delete("nvelocity.log");
            }
            catch (IOException)
            {
                // TODO: This is evil! need to investigate further. Cannot get
                // exclusive lock on the log file with this assembly now a
                // library (as opposed to an exe). However not convinced that
                // the line isn't a hangover from java conversion. Need to
                // investigate further.
                ;
            }
            base.Configure(workingDirectory, props);
            ExtendedProperties p = new ExtendedProperties();
            string templateName = props["template"];
            string templateSrc;
            if (templateName == null)
            {
                log.Info("No template file was specified, using default");
                p.SetProperty("resource.loader", "class");
                p.SetProperty("class.resource.loader.class", "NHibernate.Tool.hbm2net.StringResourceLoader;NHibernate.Tool.hbm2net");
                templateSrc =
                    new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("NHibernate.Tool.hbm2net.convert.vm")).
                        ReadToEnd();
            }
            else
            {
                // NH-242 raised issue of where NVelocity looks when supplied with a unpathed file name. Hence
                // will take responsiblity of explicitly instructing NVelocity where to look.
                if (!Path.IsPathRooted(templateName))
                {
                    templateName = Path.Combine(this.WorkingDirectory.FullName, templateName);
                }
                if (!File.Exists(templateName))
                {
                    string msg =
                        string.Format("Cannot find template file using absolute path or relative to '{0}'.",
                                      this.WorkingDirectory.FullName);
                    throw new IOException(msg);
                }

                p.SetProperty("resource.loader", "class");
                p.SetProperty("class.resource.loader.class", "NHibernate.Tool.hbm2net.StringResourceLoader;NHibernate.Tool.hbm2net");
                using (StreamReader sr = new StreamReader(File.OpenRead(templateName)))
                {
                    templateSrc = sr.ReadToEnd();
                    sr.Close();
                }
            }
            ve = new VelocityEngine();
            ve.Init(p);
            template = ve.GetTemplate(templateSrc);
        }
示例#17
0
		protected override void InitializeTask(XmlNode taskNode)
		{
			base.InitializeTask(taskNode);

			// Initializes NVelocity

			velocity = new VelocityEngine();

			ExtendedProperties props = new ExtendedProperties();
			velocity.Init(props);

			template = velocity.GetTemplate(templateFile);

			// TODO: validate all arguments are present
			
			counter = startOrder + 1;
		}
示例#18
0
 public static string GetTemplateData(string name)
 {
     template = engine.GetTemplate(name);
     return template.Data.ToString();
 }
示例#19
0
 private string MergeTemplate(Template template, VelocityContext context)
 {
     var writer =new StringWriter();
     template.Merge(context, writer);
     return writer.GetStringBuilder().ToString();
 }
		protected override void BeforeMerge(VelocityEngine velocity, Template template, IContext context)
		{
			((VelocityContext) context).AttachEventCartridge(EscapeUtils.EscapableEventCartridge);

			base.BeforeMerge(velocity, template, context);
		}