This class provides a separate new-able instance of the Velocity template engine. The alternative model for use is using the Velocity class which employs the singleton model. Please ensure that you call one of the init() variants. This is critical for proper behavior. Coming soon : Velocity will call the parameter-less init() at the first use of this class if the init() wasn't explicitly called. While this will ensure that Velocity functions, it almost certainly won't function in the way you intend, so please make sure to call init().
Example #1
2
 public void Init(IDictionary<string, string> properties)
 {
     //初始化NVelocity引擎
     var nv_properties = new Commons.Collections.ExtendedProperties();
     var prefix = this.GetType().FullName + ".";
     foreach (String key in properties.Keys.Where(t => t.StartsWith(prefix)))
         nv_properties.SetProperty(key.Substring(prefix.Length), properties[key]);
     engine = new VelocityEngine(nv_properties);
     engine.Init();
 }
Example #2
1
        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);
        }
Example #3
1
 static NVelocityHelper()
 {
     _velocity = new VelocityEngine();
     var props = new ExtendedProperties();
     props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, ConfigurationManager.AppSettings["TemplateFolder"]);
     _velocity.Init(props);
 }
Example #4
1
 static NVelocity()
 {
     filePath = Utils.GetMapPath(BaseConfigs.GetForumPath);
     engine = new VelocityEngine();
     props = new ExtendedProperties();
     props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
     props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");
     props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, filePath);
     engine.Init(props);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="NVelocityViewEngine"/> class.
        /// </summary>
        /// <param name="assemblies">The assemblies.</param>
        /// <param name="extensionMethodTypes">The extension method types.</param>
        public NVelocityViewEngine(IEnumerable<Assembly> assemblies, params Type[] extensionMethodTypes)
        {
            var properties = new ExtendedProperties();
            properties.AddProperty("resource.loader", "parials");
            properties.AddProperty("parials.resource.loader.class", typeof(PartialFileResourceLoader).AssemblyQualifiedName.Replace(",", ";"));
            properties.AddProperty("parials.resource.loader.assembly", assemblies.Select(a => a.FullName).ToList());
            _engine = new VelocityEngine();
            _engine.Init(properties);

            _extensionMethods = extensionMethodTypes.SelectMany(type => type.GetMethods(BindingFlags.Public | BindingFlags.Static)).Select(method => new DynamicDispatchMethod(method)).ToArray();
        }
 private static string ApplyTemplate(string template, VelocityContext context)
 {
     VelocityEngine velocity = new VelocityEngine();
     ExtendedProperties props = new ExtendedProperties();
     velocity.Init(props);
     using (var writer = new StringWriter(CultureInfo.CurrentCulture))
     {
         velocity.Evaluate(context, writer, string.Empty, template);
         return writer.GetStringBuilder().ToString();
     }
 }
Example #7
1
 static HtmlPage()
 {
     Engine = new VelocityEngine();
     //Engine = NVelocityTemplateEngine.NVelocityEngineFactory.CreateNVelocityAssemblyEngine(Assembly.GetExecutingAssembly().GetName().Name, false);
     //Engine = NVelocityTemplateEngine.NVelocityEngineFactory.CreateNVelocityMemoryEngine(true);
     var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("WebServerTestApp.Views.default.aspx.htm");
     var sr = new StreamReader(stream);
     template = sr.ReadToEnd();
     sr.Dispose();
     ExtendedProperties props = new ExtendedProperties();
     Engine.Init(props);
 }
        /// <summary>
        /// Merge the specified Velocity template with the given model and write
        /// the result to the given Writer.
        /// </summary>
        /// <param name="velocityEngine">VelocityEngine to work with</param>
        /// <param name="templateLocation">the location of template, relative to Velocity's resource loader path</param>
        /// <param name="encoding">encoding the encoding of the template file</param>
        /// <param name="model">the Hashtable that contains model names as keys and model objects</param>
        /// <param name="writer">writer the TextWriter to write the result to</param>
        /// <exception cref="VelocityException">thrown if any exception is thrown by the velocity engine</exception>		
        public static void MergeTemplate(
            VelocityEngine velocityEngine, string templateLocation, string encoding, Hashtable model, TextWriter writer) {

            try {
                VelocityContext velocityContext = new VelocityContext(model);
                velocityEngine.MergeTemplate(templateLocation, encoding, velocityContext, writer);
            } catch (VelocityException) {
                throw;
            } catch (Exception ex) {
                throw new VelocityException(ex.ToString(), ex);
            }
        }
		public void Setup()
		{
			items = new ArrayList();

			items.Add("a");
			items.Add("b");
			items.Add("c");
			items.Add("d");

			ve = new VelocityEngine();
			ve.Init();
		}
	/// <summary>
	/// Sole public CTOR.  We rely on the caller to give us a
	/// VelocityEngine ready with all macros registered.
	/// The context is the callers context with all tools and
	/// style drek.
	/// </summary>
	public Transformer(VelocityEngine ve, TemplateHandler th, IContext context, Hashtable applicationValues, bool validate) {
	    this.ve = ve;
	    this.baseContext = context;
	    this.templateHandler = th;

	    appValue = applicationValues;
	}
Example #11
0
		public void Setup()
		{
			context = new VelocityContext();

			ve = new VelocityEngine();
			ve.Init();
		}
Example #12
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;
 }
Example #13
0
        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);
                }
            }
        }
        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 SetUp()
		{
			ve = new VelocityEngine();
			ve.Init();

			ctx = new VelocityContext();
		}
Example #16
0
        /// <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;
        }
        /// <summary>
        /// Merge the specified Velocity template with the given model into a string.
        /// </summary>
        /// <param name="velocityEngine">VelocityEngine to work with</param>
        /// <param name="templateLocation">the location of template, relative to Velocity's resource loader path</param>
        /// <param name="encoding">the encoding string to use for the merge</param>
        /// <param name="model">the Hashtable that contains model names as keys and model objects</param>       
        /// <returns>the result as string</returns>
        /// <exception cref="VelocityException">thrown if any exception is thrown by the velocity engine</exception>		
        public static string MergeTemplateIntoString(
            VelocityEngine velocityEngine, string templateLocation, string encoding, Hashtable model) {

            StringWriter result = new StringWriter();
            MergeTemplate(velocityEngine, templateLocation, encoding, model, result);
            return result.ToString();
        }
		public void Initialize()
		{
            ActiveRecordStarter.Initialize( new XmlConfigurationSource("activeRecord.xml"),
              typeof(Acl) ,
              typeof(Category) ,
              typeof(Chat) ,
              typeof(ChatMessage) ,
              typeof(ConfigCombo) ,
              typeof(ConfigModel) ,
              typeof(Container) ,
              typeof(Content) ,
              typeof(DataModel) ,
              typeof(Field) ,
              typeof(FieldTemplate) ,
              typeof(CastlePortal.File) ,
              typeof(Forum) ,
              typeof(ForumFolder) ,
              typeof(ForumMessage) ,
              typeof(Group) ,
              typeof(Menu) ,
              typeof(Role) ,
              typeof(CastlePortal.Template) ,
              typeof(CastlePortal.Type) ,
              typeof(Language),
              typeof(MenuTranslation),
              typeof(TypeTranslation),
              typeof(User)
           );
           
           velocity = new VelocityEngine();
           ExtendedProperties props = new ExtendedProperties();
           velocity.Init(props);
		}
        public string RenderTemplate(string masterPage, string templateName, IDictionary<string, object> data)
        {
            if (string.IsNullOrEmpty(templateName))
            {
                throw new ArgumentException("The \"templateName\" parameter must be specified", "templateName");
            }

            var name = !string.IsNullOrEmpty(masterPage)
                 ? masterPage : templateName;

            var engine = new VelocityEngine();
            var props = new ExtendedProperties();
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, _templatesPath);
            engine.Init(props);
            var template = engine.GetTemplate(name);
            template.Encoding = Encoding.UTF8.BodyName;
            var context = new VelocityContext();

            var templateData = data ?? new Dictionary<string, object>();
            foreach (var key in templateData.Keys)
            {
                context.Put(key, templateData[key]);
            }

            if (!string.IsNullOrEmpty(masterPage))
            {
                context.Put("childContent", templateName);
            }

            using (var writer = new StringWriter())
            {
                engine.MergeTemplate(name, context, writer);
                return writer.GetStringBuilder().ToString();
            }
        }
        /// <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);
            }
        }
Example #21
0
 private VelocityEngine CreateVelocityEngine()
 {
     var velocity = new VelocityEngine();
     var props = new ExtendedProperties();
     props.SetProperty("file.resource.loader.path", _templateDirectory);
     velocity.Init(props);
     return velocity;
 }
 /// <inheritdoc />
 public VelocityEngine CreateVelocityEngine()
 {
     var properties = new ExtendedProperties();
     SetupVelocityEngine(properties);
     var engine = new VelocityEngine(properties);
     engine.Init();
     return engine;
 }
        public NVelocityTemplateRepository(string templateDirectory)
        {
            engine = new VelocityEngine();
            ExtendedProperties props = new ExtendedProperties();
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templateDirectory);

            engine.Init(props);
        }
 private static string EvaluateTemplate(VelocityEngine engine, IContext context, string templateString)
 {
     using (var writer = new StringWriter())
     {
         engine.Evaluate(context, writer, "", templateString);
         return writer.GetStringBuilder().ToString();
     }
 }
Example #25
0
        public Helper()
        {
            vltEngine = new VelocityEngine();
            vltEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            vltEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, AppDomain.CurrentDomain.BaseDirectory);

            vltEngine.Init();
        }
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="velocityEngine">The velocity engine</param>
        /// <param name="velocityContext">The current velocity context.</param>
        /// <param name="reportWriter">The report writer</param>
        /// <param name="templatePath">The template path.</param>
        /// <param name="contentType">The content type of the report.</param>
        /// <param name="extension">The extension of the report file.</param>
        /// <param name="helper">The formatting helper class.</param>
        /// <param name="pageSize">The number of test steps displayed in one page.</param>
        public MultipleFilesVtlReportWriter(VelocityEngine velocityEngine, VelocityContext velocityContext, IReportWriter reportWriter, string templatePath, string contentType, string extension, FormatHelper helper, int pageSize)
            : base(velocityEngine, velocityContext, reportWriter, templatePath, contentType, extension, helper)
        {
            if (pageSize <= 0)
                throw new ArgumentOutOfRangeException("size", "Must be greater than zero.");

            this.pageSize = pageSize;
        }
Example #27
0
 private VelocityEngine GetInitialisedEngine()
 {
     VelocityEngine engine = new VelocityEngine();
     ExtendedProperties properties = new ExtendedProperties();
     properties.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
     properties.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, agencyService.CurrentAgency.TemplateDirectory);
     engine.Init(properties);
     return engine;
 }
Example #28
0
File: Program.cs Project: dun3/dun3
        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;
        }
Example #29
0
 public TemplateHelper(string templatePath)
 {
     velocity = new VelocityEngine();
     ExtendedProperties props = new ExtendedProperties();
     props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templatePath);
     props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
     velocity.Init(props);
     context = new VelocityContext();
 }
        public virtual bool Configure()
        {
            _engine = new VelocityEngine();
            var props = new ExtendedProperties();
            props.AddProperty("file.resource.loader.path", TemplatePath);
            _engine.Init(props);

            return true;
        }
Example #31
0
        /// <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);
        }