Link / include css in FreeMarker using Spring 3 MVC

advertisements

I am currently trying to include a css file in my FreeMarker *.ftl. I also have configured a resource folder in my servlet config xml file.

<mvc:resources mapping="/resources/**" location="/resources/" />

But how can I access my css file from my FreeMarker template?

I simply tried the following but without success.

<link href="/resources/css/style.css" rel="stylesheet"  type="text/css" />

The resource folder lies in the root of my spring MVC 3.0 application.

/web
  /resources
    /img
    /css
  /WEB-INF
    /templates

My Servlet root is defined as:

<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/web/*</url-pattern>
</servlet-mapping>

My FreeMarker files are lying in the templates folder.


I have found two solutions. One with spring macros and one without in my FreeMarker file.

The simplest way is to use it without macros:

<link rel="stylesheet" type="text/css"
href="/springmvc/resources/css/style.css" />

In this solution I have to define the complete path.

By using spring macros you have to lay your spring.ftl into your template directory and include it in each FreeMarker template where you like to use it.

<#import "spring.ftl" as spring />
<html>
<head>
<title>...</title>
<link rel="stylesheet" type="text/css"
    href="<@spring.url '/resources/css/style.css'/>"/>
...

The spring macros can also be used for other things this blog gives a good overview.