Showing posts with label FreeMarker. Show all posts
Showing posts with label FreeMarker. Show all posts

Thursday, 29 August 2013

FreeMarker Reminders

A small post to aggregate notes related to FreeMarker.

Accessing Parameter Inside A Directive

The following piece of code:
    <#assign myVar = ${myValue}-1>
will trigger the following exception:
    Exception in thread "main" freemarker.core.ParseException:
      Encountered "{" ...
One should not use ${...} inside a FreeMarker directive, but rather:
    <#assign myVar = myValue - 1 >
See StackOverflow question.

How To Test A Boolean Value

This is how to test the enableAds boolean parameter value:
    <#if enableAds>
        ${AdsTopLeft}
    <#else>
        <img src="./incl/AdsSubstitute160-600.jpg">
    </#if>

Miscellaneous

Testing a value (if)Does a parameter/variable exist?

Friday, 26 October 2012

Spring FreeMarker Integration Example (With Annotations)

This post provides a simple example of FreeMarker integration within a Spring application. It is based on the Spring MVC With Annotations example. The code is available on GitHub in the Spring-FreeMarker-Integration directory.

FreeMarker also offers two great tutorials: the Template Author's Guide and the Programmer's Guide.

Configuration

We need to modify our Web configuration to set a FreeMarker viewer and a FreeMarker configurer:
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.jverstry")
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ViewResolver getViewResolver() {

        FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
        resolver.setCache(false);
        // resolver.setPrefix("");
        resolver.setSuffix(".ftl");

        return resolver;

    }

    @Bean
    public FreeMarkerConfigurer getFreemarkerConfig() {

        FreeMarkerConfigurer result = new FreeMarkerConfigurer();
        result.setTemplateLoaderPath("WEB-INF/pages/");

        return result;

    }

}
Our controller remains very simple:
@Controller
public class MyController {

    @RequestMapping(value = "/")
    public String home(Model model) {

        model.addAttribute("MsTime", System.currentTimeMillis());

        return "Home";

    }

}

FreeMarker Template

We use a simple FreeMarker template:
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Spring FreeMarker Example !!!</title>
</head>
<body>
    This is the Spring FreeMarker Example !!!

    Time is: ${MsTime}!
</body>
</html>

Maven Dependency

We need the following dependency:
 <dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.19</version>
</dependency>

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:

  http://localhost:8282/spring-freemarker-integration/.

The home page will display:



More Spring related posts here.