C# template engine velocity




















Viewed 71k times. Improve this question. Peter Mortensen See also stackoverflow. You can easily generate formatted text output from source template, input variables, and. NET classes with a few lines of code. The following TemplateEngine thedownloadplanet. NET, Silverlight and. NET Compact Framework. Add a comment. Active Oldest Votes. Improve this answer. David Sykes Paolo Tedesco Paolo Tedesco One more thing that should be pointed out is that this is a templating engine with C syntax.

So there's no need to learn new templating syntax. Malkov Malkov 1 1 gold badge 6 6 silver badges 8 8 bronze badges. Here's an example of the syntax from the documentation: Smart. Scott Rippey Scott Rippey If you want to look at it, the code is available in my class library from my Subversion repository or web page: Subversion repository of source code Subversion repository of binaries , contains latest checked in source code that builds and passes unit tests For the subversion repositories you need a username and password, both are "guest", without the quotes.

The code is in the LVK. Lasse V. Karlsen Lasse V. Karlsen k 95 95 gold badges silver badges bronze badges. I don't quite understand why you have re-invented ASP. Considering I'm using it to generate code inside Visual Studio, amongst other things, I don't think it would be feasible to set up a full ASP.

NET engine locally for that. I think you would balk at StringTemplate, as referred to by others to have a requirement that you would need a full IIS configuration set up for this. The default reference name is "bodyContent" e. This block macro feature was introduced in Velocity 1. Set it to true if you need a local namespace in macros or more advanced break controls.

Set it to true if you happen to need a namespace just for your macro's body content or more advanced break controls. New in Velocity 1. This setting will also throw an exception if an attempt is made to call a non-existing property on an object or if the object is null. When this property is true then property 'directive. Also, 'directive. For a complete discussion see Strict References Setting. This escape behavior is of use in strict mode since unintended strings of characters that look like references or macros will throw an exception.

This provides an easy way to escape these references. However, even in non-strict mode the developer may find this a more consistent and reliable method for escaping.

Note that a VTL StringLiteral is specifically a string using double quotes that is used in a set statement, a method call of a reference, a parameter to a VM, or as an argument to a VTL directive in general. See the VTL reference for further information.

Affects all math operations in VTL. If changed to true, this will cause Velocity to throw a MathException whenever one side of a math operation has a null value e. If this value is left false , then rendering will continue and that math operation will be ignored. This property selects the implementation for the parser pool.

This class must implement ParserPool. Generally there is no reason to change this though if you are building a high volume web application you might consider including an alternate implementation that automatically adjusts the size of the pool. This property is used by the default pooling implementation to set the number of parser instances that Velocity will create at startup and keep in a pool.

The default of 20 parsers should be more than enough for most uses. In the event that Velocity does run out of parsers, it will indicate so in the log, and dynamically create overflow instances as needed.

Note that these extra parsers will not be added to the pool, and will be discarded after use. This will result in very slow operation compared to the normal usage of pooled parsers, but this is considered an exceptional condition. A web application using Velocity as its view engine might exhibit this behavior under extremely high concurrency such as when getting Slashdotted. If you see a corresponding message referencing the parser. This property sets the 'Uberspector', the introspection package that handles all introspection strategies for Velocity.

You can specify a comma-separated list of Uberspector classes, in which case all Uberspectors are chained. The default chaining behaviour is to return the first non-null value for each introspection call among all provided uberspectors.

You can modify this behaviour for instance to restrict access to some methods by subclassing org. AbstractChainableUberspector or implementing directly org. This allows you to create more interesting rules or patterns for Uberspection, rather than just returning the first non-null value. Velocity has a few nice logging features to allow both simplicity and flexibility. Without any extra configuration, Velocity will setup a file-based logger that will output all logging messages to a file called velocity.

For more advanced users, you may integrate your current logging facilities with Velocity to have all log messages sent to your logger. Starting with version 1. It will do so by using whatever it finds in the current classpath, starting first with Logkit.

If Logkit isn't found, it tries Log4j. To utilize this feature, simply use the 'non-dependency' Velocity jar because Logkit is baked into the jar with dependencies and place either the logkit or log4j jar in your classpath. By default, Velocity will create a file-based logger in the current directory.

See the note above regarding automatic detection of Logkit or Log4j to use as the default logging system. To use this feature you must. Note that this support for Logger is in version 1. Further, in version 1. We apologize for the confusion, but we needed to move on. You can create a custom logging class - you just need to implement the interface org.

LogChute and then simply set the configuration property runtime. You may specify the classname as you specify any other properties. See the information on the Velocity helper class as well as the Configuration keys and values. Please note that the old org. LogSystem interface has been deprecated for v1. This is due to significant upgrades to our logging code that could not be supported by the LogSystem interface. But don't worry, if you specify a custom class that implements the LogSystem interface, it will still work.

However, it will generate deprecation warnings. You should upgrade your custom logger to implement LogChute as soon as possible.

You can integrate Velocity's logging capabilities with your applications existing logging system, simply by implementing the org. LogChute interface. Then, pass an instance of your logging class to Velocity via the runtime. Here is an example of how to use an instantiation of your class that implements Velocity's logging system as the logger. Note that we are not passing the name of the class to use, but rather a living, existing instantiation of the class to be used. All that is required is that it support the LogChute interface.

One of the fundamental and important parts about Velocity is the resource management system and the resource loaders. They are referred to as 'resources' here rather than 'templates' because the resource management system will also handle non-template reasources, specifically things that are loaded via the include directive.

The resource loader system if very flexible, allowing one or more resource loaders to be in operation at the same time. This allows tremendous flexibility in configuration and resource managment, and futher allows you to write your own resource loaders for your special needs.

There are currently four kinds of resource loaders that are included with Velocity, each described below. Note that in the example configuration properties given, a common name for the loader is shown ex. This 'common name' may not work for your configuration. Please read the section on resource configuration properties to understand how this system works.

Also, each of these loaders is located in the package org. FileResourceLoader : This loader gets resources from the filesystem. Its configuration properties include:. This is the default loader, and is configured, by default to get templates from the 'current directory'. In the case of using Velocity with servlets, this can be a problem as you don't want to have to keep your templates in the directory from which you start your servlet engine.

See the documentation for your servlet or web framework for example VelocityViewServlet for more info on how to configure the location of the Velocity templates. JarResourceLoader : This loader gets resource from specific jar files. It is very similar to the FileResourceLoader, except that you have the convenience of bundling your templates into jars.

The properties are identical, except for jar. To specify a jar for the loader. ClasspathResourceLoader : This loader gets resources from the classloader. In general, this means that the ClasspathResourceLoader will load templates placed in the classpath in jars, for example While the classpath is a source of great pain and suffering in general, it is a very useful mechanism when working on a Servlet Spec 2.

Tomcat is an example of such. There are no configuration options to worry about, nor is the absolute vs. Again, please note that the ClasspathResourceLoader is not only for use with a servlet container, but can be used in any application context. This loader simply downloads resources from configured URLs. It works much like the FileResourceLoader, however, it can pull templates down from any valid URL to which the application can create a connection. This loader is only available under JDK 1.

For more information on this loader, please see the javadoc for the class org. Configuring the resource loaders for Velocity is straightforward. The properties that control the are listed in the resource configuration section, for further reference.

The first step in configuring one or more resource loaders is do 'declare' them by name to Velocity. Use the property resource. You can use anything you want - these names are used to associate configuration properties with a given loader. That entry declares that we will have a resource loader known as 'file'.

The next thing to do is to set the important properties. The most critical is to declare the class to use as the loader:. In this case, we are telling velocity that we are setting up a resource loadercalled 'file', and are using the class org.

FileResourceLoader to be the class to use. The next thing we do is set the properties important to this loader. Here, we set a few things. Second, we turned caching on, so that after a template or static file is read in, it is cached in memory.

And finally, we set the modification check interval to 2 seconds, allowing Velocity to check for new templates. Do-nothing Default Configuration: As the name says, there is nothing you have to do or configure to get the default configuration. This configuration uses the FileResourceLoader with the current directory as the default resource path, and caching is off.

As a properties set, this is expressed as:. Multiple Template Path Configuration: This configuration uses the FileResourceLoader with several directories as 'nodes' on the template search path. We also want to use caching, and have the templates checked for changes in 10 second intervals.

This would allow you to qickly drop a template into the file template area to replace on of the templates found in the classpath usually via a jar without having to rebuild the jar. Node that the three names 'file', 'class', and 'jar' are merely for your convenience and sanity. They can be anything you want - they are just used to associate a set of properties together.

However, it is recommended that you use names that give some hint of the function. Note that while all three require very little configuration information for proper operation, the ClasspathResourceLoader is the simplest. The Resource Manager is the main part of the resource template and static content management system, and is responsible for taking application requests for templates, finding them in the available resource loaders, and then optionally caching the parsed template.

The Resource Cache is the mechanism that the Resource Manager uses to cache templates for quick reuse. While the default versions of these two facilities are suitable for most applications, for advanced users it now is possible to replace the default resource manager and resource cache with custom implementations.

A resource manager implementation must implement the org. ResourceManager interface. A description of the requirements of a resource manager is out of scope for this document. Implementors are encouraged to review the default implementation. To configure Velocity to load the replacement implementation, use the configuration key:. A resource cache implementation must implement the org.

ResourceCache interface As with the resource manager, a description of the requirements of a resource manager is out of scope for this document. This key is also defined as a contstant RuntimeConstants.

A resource cache implementation may want to limit the cache size rather than providing an unbounded cache which could consume all available memory. To configure Velocity to set the size for your cache, use the configuration key:. Velocity allows you to specify the character encoding of your template resources on a template by template basis. The normal resource API's have been extended to take the encoding as an argument:. For the official names for character sets, see here.

Note that this applies only to the encoding of the template itself - the output encoding is an application specific issue. Velocity's flexibility and simple template language makes it an ideal environment for working with XML data.

The Jakarta site is also rendered using Anakia. For example, start with an XML document such as:. See the Anakia source for details on how to do this, or the Anakia example in the examples directory in the distribution.

Of course, this isn't the prettiest of examples, but it shows the basics - that you can easily access XML data directly from a Velocity template. One real advantage of styling XML data in Velocity is that you have access to any other object or data that the application provides. You aren't limited to just using the data present in the XML document. You may add anything you want to the context to provide additional information for your output, or provide tools to help make working with the XML data easier.

One technique is to combine the use of Velocimacros when you need to render an entity into the output stream:. Another trick would be to create an encoding utility that takes the context as a constructor parameter and only implements a method:.

Alternatively, since Velocity makes it easy to implement custom Context objects, you could implement your own context which always applies the encoding to any string returned. Be careful to avoid rendering the output of method calls directly, as they could return objects or strings which might need encoding.

Place them first into the context with a set directive and the use that, for example:. The previous suggestions for dealing with XML entities came from Christoph Reck, an active participant in the Velocity community. We hope this brief guide was a helpful introduction to using Velocity in your Java projects, and thank you for you interest in Velocity. We welcome any and all comments you may have about this documentation and the Velocity template engine itself.

Please submit all detailed, thoughtful and constructive feedback through our mailing lists. IncludeEventHandler org. InvalidReferenceEventHandler org. MethodExceptionEventHandler org.

NullSetEventHandler org. StringWriter ; import org. VelocityContext ; import org. Template ; import org. Velocity ; import org. ResourceNotFoundException ; import org. ParseErrorException ; import org. MethodInvocationException ; Velocity. Template ; VelocityEngine ; import org. The value is typically a String, but in special cases can also be a comma-separated list of values in a single String, ex.

If prompted, import other packages of velocity. The project structure is as follows:. Next, start using velocity template engine , create the directory templates in SRC, and create files in the templates directory test. Velocity is a Java based template engine. There are three ways to load templates: 1.

Load from the file path; 2. From the classpath myvelocity Java uses this method ; 3.



0コメント

  • 1000 / 1000