Example #1
0
        public void Test_Example1()
        {
            String templateFile = "example1.vm";
            try {
            /*
             * setup
             */

            Velocity.SetProperty(NVelocity.Runtime.RuntimeConstants_Fields.FILE_RESOURCE_LOADER_PATH, "../test/templates");
            Velocity.Init();

            /*
             *  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 = Velocity.GetTemplate(templateFile)
            ;
            } catch( ResourceNotFoundException rnfe ) {
            Console.Out.WriteLine("Example : error : cannot find template " + templateFile + " : \n" + rnfe.Message);
            Assertion.Fail();
            } catch( ParseErrorException pee ) {
            Console.Out.WriteLine("Example : Syntax error in template " + templateFile + " : \n" + pee );
            Assertion.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(System.Exception ex) {
            Console.Out.WriteLine(ex);
            Assertion.Fail();
            }
        }