【问题标题】:How to work with FreeMarker如何使用 FreeMarker
【发布时间】:2015-08-15 19:23:36
【问题描述】:

我使用 FreeMarker。我现在需要的是 smarty (php world) 中的模板继承。

我有一个 base.ftl,所有的 javascript 和 css 内容都将被加载:

简体:

<html>  
    <head>
        <title>MyApp</title>
    </head>
    <body>
        ${content}
    </body>
</html>

假设我有一个用于列出用户的模板 (users.ftl):

<ul>
   <li>User1</li>
   <li>User2</li>
</ul>

我做了一些研究,发现我可以使用&lt;#include "..."&gt;,但我相信还有另一种优雅的方式。

还有一个问题:如果我想在 ${content} 中添加 users.ftl AND products.ftl 的输出怎么办:

<ul>
   <li>Product1</li>
   <li>Product2</li>
</ul>

控制器的外观如何? 目前我的样子:

package org.domain.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller("indexController")
public class IndexController {

    @RequestMapping("/login")
    public String indexAction(Model model) {
        model.addAttribute("content", "How to get the output of users.ftl and products.ftl??");
        return "base";
    }

}

【问题讨论】:

  • 查看命名空间并导入。 freemarker.org/docs/dgui_misc_namespace.html
  • 我会使用#import+#macro 而不是#include,但这在方法上并没有太大的不同。那么为什么你希望它成为一个变量呢?此外,您可以在数据模型中指定实际内容模板的名称,而不是其输出。
  • 或者,也许这个动作应该直接使用你在这里调用的content.ftl,而content.ftl应该像&lt;@base.page&gt;...&lt;/@base.page&gt;或其他东西一样将base.ftl拉到自己周围。
  • 实际上,我只是想要一个基本模板,在其中定义我所有视图共有的所有脚本和样式标签。在我的控制器中,我希望能够创建任意数量的视图并显示它们。目前我只能通过返回 ftl 文件的名称在我的控制器中调用一个模板。
  • 考虑为您的项目添加 apache tile,它与 ftl 和 spring 很好地集成,提供开箱即用的模板继承。

标签: java spring spring-mvc freemarker


【解决方案1】:
    Sample pom
     <!-- Spring boot capacity added -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-freemarker</artifactId>
            </dependency>
    

模板配置示例类:

        import java.io.File;
        import java.io.IOException;
               
        import freemarker.cache.FileTemplateLoader;
        import freemarker.template.Configuration;
        import freemarker.template.TemplateExceptionHandler;
        
        public class TemplateConfig {
        
            private static Configuration configuration;
        
            private TemplateConfig() {
                buildCodegenConfig();
            }
            
            public static Configuration get() {
                new TemplateConfig();
                return configuration;
            }
        
            private static void buildCodegenConfig() {
        
                configuration = new Configuration(Configuration.VERSION_2_3_29);
                configuration.setDefaultEncoding("UTF-8");
        
                // Sets how errors will appear.
                configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        
                // Don't log exceptions inside FreeMarker that it will thrown at you anyway:
                configuration.setLogTemplateExceptions(false);
        
                // Wrap unchecked exceptions thrown during template processing into
                // TemplateException-s:
                configuration.setWrapUncheckedExceptions(true);
        
                // Do not fall back to higher scopes when reading a null loop variable:
                configuration.setFallbackOnNullLoopVariable(false);
                
                try {
                    FileTemplateLoader templateLoader = new FileTemplateLoader(new File("src/main/resources/templates"));
                    configuration.setTemplateLoader(templateLoader);
                } catch (IOException e) {
                    e.printStackTrace();
                }
        
            }
        }
    
    //Sample template fetcher
    
    import freemarker.cache.FileTemplateLoader;
    import freemarker.template.Configuration;
    import freemarker.template.Template;
    
    
    public class TemplateFetcher {
        
        private static Configuration configuration = TemplateConfig.get();
        
        public static Template getTemplate(String tempplateName) {
            try {
                FileTemplateLoader templateLoader = new FileTemplateLoader(new File("src/main/resources/templates"));
                configuration.setTemplateLoader(templateLoader);
                return configuration.getTemplate(tempplateName);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    
    }


//sample pojos

public class PageBean {
     private List<QuestionBean> questionsList;
}

public class QuestionBean {
    
    private String questionName;
    private String id;
    private String labelText;
    private String eventAttributeKey;
    private String refDataSetName;
    private String required;
    private String optionsAvailable;
    private String questionType;
    private String orderedBy;
}
    
    //sample code to read freemarker template (.ftlh) and write the file
    
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.Writer;
    import java.util.Map;
    
    import TemplateFetcher;
    
    import freemarker.template.Template;
    
    public class CodeWriter {
    
        public static void writeSourceCodeFile(Map<Object, Object> dataMap) {
//This datamap holds an object "pageBean" which has list of another object "question" which I'm not showing here.           

Writer fileWriter = null;
    
            String packageNameFolder = "C:\\Users\\abc\\destinationFolder";
    
            String fileName = "xyz.html";
    
            try {
                new File(packageNameFolder).mkdirs();
                fileWriter = new FileWriter(new File(packageNameFolder + File.separator + fileName));
                Template template = TemplateFetcher.getTemplate("htmlFile.ftlh");
                template.process(dataMap, fileWriter);
                fileWriter.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
    
                try {
                    if (null != fileWriter) {
                        fileWriter.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
        }
    }


//sample htmlFile.ftlh

<#list pageBean.questionsList as eachQuestion> 
    ${eachQuestion.questionName}("${eachQuestion.id}", "${eachQuestion.labelText}", <#if eachQuestion.eventAttributeKey?has_content>"${eachQuestion.eventAttributeKey}" <#else>EMPTY</#if>, <#if eachQuestion.refDataSetName?has_content>"${eachQuestion.refDataSetName}" <#else>EMPTY</#if>, ${eachQuestion.required}, ${eachQuestion.optionsAvailable}, ${eachQuestion.questionType}, ${eachQuestion.orderedBy})<#sep>,
</#list>;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-26
    • 2012-06-04
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 2011-12-02
    • 2018-07-09
    相关资源
    最近更新 更多