Home  >  Article  >  php教程  >  FreeMarker arrangement (Configuration)

FreeMarker arrangement (Configuration)

高洛峰
高洛峰Original
2017-01-05 13:25:362149browse

p> Basic

Configuration is an object that stores application level public configuration information and global shared variables that can be used by templates. At the same time, it is also responsible for the creation and caching of template instances. A Configuration is actually an instance of the freemarker.template.Configuration object, created using its constructor. Typically applications use a shared single-instance Configuration object.

Configuration objects can be used by methods of the Template object. Each template instance is associated with a Configuration instance, which is associated through the Template constructor. Usually you use this method to obtain Configuration.getTemplate Template object.

Shared variables

Shared variables are those variables defined for use by all templates (Template). You can add shared variables through the setSharedVariable method of the configuration object.

Configuration cfg = new Configuration(); ... cfg.setSharedVariable("wrap", new WrapDirective()); cfg.setSharedVariable("company", "Foo Inc."); // Using ObjectWrapper .DEFAULT_WRAPPER

All template instances associated with the configuration object can obtain the string by obtaining the to_upper converter and company, so you do not need to add these variables to the root again and again. . If you add a variable with the same name to root, your newly added variable will overwrite the previous shared variable.

warn!

If the configuration object is called by multiple threads, do not use TemplateModel implementation classes as shared variables because they are not thread-safe, such as servlet-based web sites.

Configuration object already contains some shared converter variables when initialized:

Name class

name class capture_output freemarker.template.utility.CaptureOutput compress freemarker.template.utility.StandardCompress html_escape freemarker.template.utility.HtmlEscape normalize_newlines freemarker.template.utility.NormalizeNewlines xml_escape freemarker.template.utility.XmlEscape

Configuration parameters

Configuration parameters are those named that can affect the running behavior of FreeMarker parameter. For example locale,number_format.

Configuration parameters are stored in the Configuration instance, which can be modified by the template instance (Template). For example, if you set locale equal to "en_US" in Configuration, all template objects will use "en_US" unless you modify the default configuration using the setLocale method in a single template instance. Therefore, the parameters set by the configuration can be regarded as the default parameters, which can be overridden by the parameters set by the Template level, and the parameter information set by both of them can be overwritten by the parameters set in the environment (that is, set by the template file instructions) As follows:

${1.2}<#setting locale="en_US">${1.2}

You can imagine this calling method as three layers (configuration object layer, template Layer, running environment layer) The following table shows the parameter settings for each layer:

Setting A Setting B Setting C Setting D Setting E Setting F Layer 3: Environment 1 - - 1 - - Layer 2: Template 2 2 - - 2 - Layer 1:Configuration 3 3 3 3 - -

Then the final results of the configuration parameters are: A = 1, B = 2, C = 3, D = 1, E = 2. The F parameter is likely to be null.

If you want to query the list of settable parameters, you can consult the following two parts of the FreeMarker API documentation:
Configuration of all layers

freemarker.core.Configurable.setSetting(String, String)

Coniguration layer configuration

freemarker.template.Configuration.setSetting(String,String)


Loading template

Template loader

The template loader is the object that loads the original data based on the abstract path ("index.ftl" or "products/catalog.ftl"), and what kind of resources are loaded (file data in the directory or data in the database) depends on the specific loader implementation. When you call cfg.getTemplate, FreeMarker will ask you for the template loader you previously configured for the Configuration object. The template loader is responsible for loading the file.

Built-in template loader
You can use the following three methods to set the three methods of template loading

void setDirectoryForTemplateLoading(File dir);

or

void setClassForTemplateLoading(Class cl, String prefix);

or

void setServletContextForTemplateLoading(Object servletContext, String path);

The first way above Display specifies a directory in the file system. FreeMarker will record the template in this directory. Needless to say, this directory must exist, otherwise an exception will be thrown.

The second method uses a Class as an input parameter. When you want to use ClassLoader to load the template, you can use this method. This method will be called to find the template file. At the same time, this method of template loading is more stable than the previous one, especially in production systems. You can easily package resource files, icons, etc. into .jar files.

The third method takes the context of the web application and the base path (relative to the parent path of WEN-INF) as parameters. This style of template loader will load templates from the web application context.

Loading templates from multiple locations

If you want to load templates from multiple locations, you can create individual template loaders corresponding to different locations, and then wrap them in a name Call MultiTemplateLoader in the template loader, and finally set it to the Configuration object through the method setTemplateLoader(TemplateLoader loader). Here is an example of loading templates from two different locations:

import freemarker.cache.*; // template loaders live in this package ... FileTemplateLoader ftl1 = new FileTemplateLoader(new File("/tmp/templates")); FileTemplateLoader ftl2 = new FileTemplateLoader(new File("/usr/data/templates")); ClassTemplateLoader ctl = new ClassTemplateLoader(getClass(), ""); TemplateLoader[] loaders = new TemplateLoader[] { ftl1, ftl2, ctl }; MultiTemplateLoader mtl = new MultiTemplateLoader(loaders); cfg.setTemplateLoader(mtl);

FreeMarker will first search for the template file in the path /tmp/templates. If it is not found, it will return to the path /usr/data/templates to search. If it is not found, it will try to load it using class-loader.

Get template files from other resources

If none of these built-in template loaders meet your requirements, then you can customize a template loader yourself, just implement freemarker Just use the .cache.TemplateLoader interface, and then pass it to the Configuration object through the method setTemplateLoader(TemplateLoader loader).

Caching template

FreeMarker caching template means that when you get a template through the getTemplate method, FreeMarker will not only return a Template object, but also cache the object when you next time When a template is requested with the same path, it will return the template object in the cache. If you change the template file, FreeMarker will automatically reload and re-parse the template the next time you obtain the template. Even so, if directly determining whether a file has been modified is a time-consuming operation, FreeMarker provides a configuration parameter "update delay" at the Configuration object level. This parameter means how long it takes for FreeMarker to determine the version of the template. The default setting is 5 seconds, that is, it will determine whether the template has been modified every 5 seconds. If you want to determine in real time, set this parameter to 0 . Another point to note is that not all loaders support this judgment method. For example, a template loader based on class-loader will not find that you have modified the template file.

This is how FreeMarker deletes templates in the cache. You can use the Configuration object method clearTemplateCache to manually clear the template objects in the cache. In fact, the cache part can be added to FreeMarker as a component (that is, it can use third-party caching solutions). You can do this by setting the cache_storage parameter. For most developers, the freemarker.cache.MruCacheStorage implementation that comes with FreeMarker is sufficient. This cache uses a 2-level Most Recently Used policy. At the first level, all cache entries are strongly referenced (entries are not known to the JVM, as opposed to softly referenced) until the maximum time is reached, and the least recently used entries are Migrate to the second level cache. Entries at this level use weak references until they expire. If the size of the reference and strong reference areas can be set in the constructor, for example, if you want to set the strong reference area to 20 and the weak reference area to 250, then you can use the following code:

cfg .setCacheStorage(new freemarker.cache.MruCacheStorage(20, 250))

Since MruCacheStorage is the default cache implementation, you can also set it like this:

cfg.setSetting(Configuration.CACHE_STORAGE_KEY, "strong:20, soft:250");

When you create a new Configuration, it uses MruCacheStorage cache implementation by default and the default value maxStrongSize is equal to 0, maxSoftSize is equal to Integer.MAX_VALUE (that is, the theoretical maximum value). But for high-load systems, we recommend setting maxStrongSize to a value other than 0, otherwise it will cause frequent reloading and re-parsing of templates.

Exception handling

Potential exceptions

Exceptions generated by FreeMarker can generally be classified into the following categories:

Exceptions generated by FreeMarker during the initialization phase: Usually in Your application only needs to initialize FreeMarker once, and the exception generated by the class during this period is called an initialization exception.

Exceptions during loading and parsing templates: When you obtain the template through the Configuration.getTemplate() method (if the template has not been cached before), two types of exceptions will be generated:

IOException: Because the template is not found, or other IO exceptions occur when reading the template, such as you do not have permission to read the file, etc.; freemarker.core.ParseException Because the syntax of the template file is incorrect;

Exceptions during execution: When you call the Template.process(...) method, two types of exceptions will be thrown:

IOException Errors that occur when writing data to the output; freemarker. template.TemplatException Other exceptions generated during runtime. For example, one of the most common errors is that the template references a variable that does not exist;

For more FreeMarker configuration (Configuration) related articles, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn