Andy
Andy

Reputation: 41

How can I include CSS file in freemarker

I'm making a website with spring-boot & spring-security which prefers to supply freemarker as view. I don't know ftl much, and now I need use adminLTE's CSS and JS files in my ftl, but how?

<html lang="en">
<#assign basePath=request.contextPath>
<#macro head>
    ...
    <script src="${basePath}WEB-INF/AdminLTE/dist/js/adminlte.min.js"></script>
    <link src="${basePath}WEB-INF/AdminLTE/plugins/iCheck/line/line.css" rel="stylesheet"></link>
    <script src="${basePath}WEB-INF/AdminLTE/plugins/iCheck/icheck.js"></script>
    ...
<#macro>

Upvotes: 1

Views: 19771

Answers (3)

Shtefan
Shtefan

Reputation: 808

I use this simple solution.

I created a dedicated Get method for css-s.

@GetMapping(value="/css/{cssFile}") 
    public @ResponseBody byte[] getFile(@PathVariable("cssFile") String cssFile) throws IOException {
    
            InputStream in = getClass()
                    .getResourceAsStream("/css/" + cssFile);
            try {
                return in.readAllBytes();
    
            } catch (Exception e){
                var error = new String("ERROR: css file (/css/" + cssFile + ") not found");
                return error.getBytes();
            }
        }

Now I can reference the css file in the usual html way right in .ftlh file. Just need to put my file under resources/css/ directory.

<html>
<head>
<link href="css/general.css" rel="stylesheet">

</head>
<body>
...

Please also note that the suggested method (see other responses) with include statement, will produce a html file with full content of the corresponding css file not a link to css. So if you have heavy css files expect that their content will be literally included into html files received by clients.

Upvotes: 0

Maulik Kakadiya
Maulik Kakadiya

Reputation: 1647

you can include css file by using <#include > tag, place the stylesheet in the directory and use the <#include "/{path to style sheet}/Styles.css">

and make sure your style sheet is inside the styles element:

<style type="text/css">
...
</style>

Example of this approach is

Test Template

<html>
<head>
<#include "css/test.css">
</head>
<body>
.......................
</body>
</html>

test.css

<style type="text/css">
body{background-color:#C5C5C0;}
*{font-family:Tahoma, Verdana, Helvetica, sans-serif;}
</style>

Upvotes: 5

panser
panser

Reputation: 2129

you can declare some param in code and use it to fill full path to css

// in java
params.put("htmlIncludePath", "classpath:/templates/pdfTemplates/include/");
...
// in ftl
<link href="${htmlIncludePath}manrope.css" rel="stylesheet">

physically files should be located in src/main/resources/templates/pdfTemplates/include

Upvotes: 0

Related Questions