freemarker uses String template for rendering display

We use freemarker's common writing method to configure the requested html and other static page path address methods, so as to obtain page rendering data and display it. The following is a test example on the freemarker official website. For details, see the official website link .

import freemarker.template.*;
import java.util.*;
import java.io.*;

public class Test {

    public static void main(String[] args) throws Exception {

        /* ------------------------------------------------------------------------ */
        /* You should do this ONLY ONCE in the whole application life-cycle:        */

        /* Create and adjust the configuration singleton */
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);
        cfg.setDirectoryForTemplateLoading(new File("/where/you/store/templates"));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        cfg.setLogTemplateExceptions(false);

        /* ------------------------------------------------------------------------ */
        /* You usually do these for MULTIPLE TIMES in the application life-cycle:   */

        /* Create a data-model */
        Map root = new HashMap();
        root.put("user", "Big Joe");
        Product latest = new Product();
        latest.setUrl("products/greenmouse.html");
        latest.setName("green mouse");
        root.put("latestProduct", latest);

        /* Get the template (uses cache internally) */
        Template temp = cfg.getTemplate("test.ftlh");

        /* Merge data-model with template */
        Writer out = new OutputStreamWriter(System.out);
        temp.process(root, out);
        // Note: Depending on what `out` is, you may need to call `out.close()`.
        // This is usually the case for file output, but not for servlet output.
    }
}

From the above example, the following two lines of code are our most common methods or use the modelAndView method in springmvc
cfg.setDirectoryForTemplateLoading(new File("/where/you/store/templates"));
latest.setUrl("products/greenmouse.html");

ModelAndView method

ModelAndView modelAndView = new ModelAndView("/where/you/store/templates/products/greenmouse.html");

Let's imagine that there is such a demand. There is an agreement that needs to be displayed on the pc, wap, and app side. The content is almost the same, but three copies need to be maintained because the styles, page headers and tails are different. The consequence is that technicians are required to revise frequently, and the work has no technical content. After the revision is completed, the online process has to be re-released. There are all harms and no benefits. After there are too many agreement documents, there is no need to do anything else every day. Yes, the protocol is being revised all day long. So we went to optimize the protocol review process, and the optimized flow chart is as follows.
write picture description here

We combined the three agreements into one and handed it over to the operation (you can spend the remaining time for further study). Since the system is a modular background function and the contract module is not on the same server, it is not recommended to use the method of generating template files. The optimal solution is to store the protocol template in the data, take out the template + template data ==> render and display it on the front page.

First of all, to analyze the feasibility of the solution, I chose to visit the freemarker official website to find a solution. The official website has the freemarker engine rendering flow chart as follows: For details, see freemarker

write picture description here
The process has clearly stated that the data is first rendered and then displayed. When you see it, you will know that the above scheme is feasible. Now the question is how to render the data and output the String type template?
Found the answer from freemarker's api: see api for details , freemarker.cache -> StringTemplateLoader

public class StringTemplateLoader
extends Object
implements TemplateLoader
A TemplateLoader that uses a Map with String-s as its source of templates.
In most case the regular way of loading templates from files will be fine. However, there can be situations where you don't want to or can't load a template from a file, e.g. if you have to deploy a single jar for JavaWebStart or if they are contained within a database. A single template can be created manually e.g.

   String templateStr="Hello ${user}";
   Template t = new Template("name", new StringReader(templateStr),
               new Configuration());

If, however, you want to create templates from strings which import other templates this method doesn't work.

In that case you can create a StringTemplateLoader and add each template to it:

   StringTemplateLoader stringLoader = new StringTemplateLoader();
   stringLoader.putTemplate("greetTemplate", "<#macro greet>Hello</#macro>");
   stringLoader.putTemplate("myTemplate", "<#include \"greetTemplate\"><@greet/> World!");

Then you tell your Configuration object to use it:

   cfg.setTemplateLoader(stringLoader);

The above content is roughly translated as freemarker is suitable for using String type as template source. For detailed usage, see the following actual combat code:

        StringWriter writer = new StringWriter();
        String content = "你的名字${name}";

        Configuration configuration = new Configuration();  
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        stringLoader.putTemplate("contract", content);
        configuration.setTemplateLoader(stringLoader);

        Template template = configuration.getTemplate("contract","utf-8");  
        Map<String,Object> root = new HashMap<String,Object>();    
        root.put("name", "郭啸天");  
        try {  
            template.process(root, writer);  
            System.out.println(writer.toString());    
            response.getWriter().print(writer.toString());
        } catch (TemplateException e) {  
                e.printStackTrace();  
        }

In fact, it is quite simple to implement. After all, freemarker already supports this method, and there is no need to reimplement methods and other other methods.
The above is the entire content of the blog. If you have any questions or mistakes in the above content, I hope you can point out.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325577540&siteId=291194637