I have been looking at all of the resources available on how to include an html file into another html file using Thymeleaf's th:insert. I am wondering if anyone could tell me what I am doing wrong as I feel like this html looks exactly like the examples I have seen.
My index.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.thymeleaf.org ">
<head>
<title>Default Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div th:insert="templates/Navbar :: navbar"> </div>
</body>
</html>
My Navbar.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.thymeleaf.org ">
<head>
<meta charset="UTF-8"/>
<title>NavigationBar</title>
<link rel="stylesheet" type="text/css" media="all" href="../../css/NavBar.css" th:href="#{/css/NavBar.css}" />
</head>
<body>
<div>
<div th:fragment="navbar" class="navbar">
<div class="navbar-inner">
<a th:href="#{/}" href="/home"> Home</a>
<a th:href="#{/}" href="/help">Help</a>
</div>
</div>
</div>
</body>
</html>
Also, here is my project's resource hierarchy via screen shot
If I put the code between the into the index.html and link the css file, the navbar shows up and works. So, I am not sure why the insert is not working. Here is my configuration file which has been edited based on examples below:
#Configuration
public class WebPageControllerConfig {
private SpringTemplateEngine templateEngine;
private ServletContextTemplateResolver templateResolver;
#Value("${WebController.startHour}")
public String startHour;
#Value("${WebController.endHour}")
public String endHour;
#Value("${WebController.numOfSkus}")
public int numOfSkus;
#Value("${WebController.skusToQuery}")
public File skusToQuery;
#Bean
public ClassLoaderTemplateResolver webPageTemplateResolver(){
ClassLoaderTemplateResolver webPageTemplateResolver = new ClassLoaderTemplateResolver();
webPageTemplateResolver.setPrefix("templates/");
webPageTemplateResolver.setSuffix(".html");
webPageTemplateResolver.setTemplateMode("HTML5");
webPageTemplateResolver.setCharacterEncoding(CharEncoding.UTF_8);
webPageTemplateResolver.setOrder(1);
return webPageTemplateResolver;
}
/* Old way of trying to configure
#Bean
public MessageSource messageSource() {...}
#Bean
public ServletContextTemplateResolver setTemplateResolver(){...}
#Bean
public SpringTemplateEngine setTemplateEngine() {...}
#Bean
public ViewResolver viewResolver() {...}
End of old configuration */
public String getStartHour() {return startHour;}
public String getendHour() {return endHour;}
public Object getnumOfSkus() {return numOfSkus;}
public File getSkusToQuery(){return skusToQuery;}
}
Change to
th:insert="templates/Navbar :: navbar"
and
th:fragment="navbar"
Configuration example:
import org.apache.commons.lang3.CharEncoding;
import org.springframework.context.annotation.*;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
#Configuration
public class ThymeleafConfiguration {
#Bean
#Description("Thymeleaf template resolver serving HTML 5 emails")
public ClassLoaderTemplateResolver emailTemplateResolver() {
ClassLoaderTemplateResolver emailTemplateResolver = new ClassLoaderTemplateResolver();
emailTemplateResolver.setPrefix("root folder where all thymeleaf files/");
emailTemplateResolver.setSuffix(".html");
emailTemplateResolver.setTemplateMode("HTML5");
emailTemplateResolver.setCharacterEncoding(CharEncoding.UTF_8);
emailTemplateResolver.setOrder(1);
return emailTemplateResolver;
}
}
Try with:
th:replace="/navbar::navbar"
or
th:insert="/navbar::navbar"
It works for me. No need to specify "template/navbar".
Related
All I can is viewing index.html, but when I am trying to surf to adminLogin for example all i see is:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
There was an unexpected error (type=Not Found, status=404).
here is PortfolioApplication:
#SpringBootApplication
public class PortfolioApplication {
public static void main(String[] args) {
SpringApplication.run(PortfolioApplication.class, args);
}
#GetMapping("/")
public String getMainPage() {
return "index.html";
}
#GetMapping("/adminLogin")
public String getAboutPage() {
return "adminLogin.html";
}
}
when i am trying to call another pages from index.html nothing happens:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hotel_Management_java_project</title>
<link rel="stylesheet" href="css/home.css">
</head>
<body>
<div class="home" id="home">
<nav>
<div class="logo">
<a href="#">
<h2>TourAgency</h2>
</a>
</div>
<div class="header_content">
<ul>
<li>Главная</li>
<div class="login">
<button class="loginbtn" id="loginbtn">Вход</button>
<div class="Login_content">
<a th:href="#{/adminLogin}">Вход для админа</a>
<a th:href="#{/employeelogin}">Вход для работника</a>
<a th:href="#{/userlogin}">Вход для пользователя</a>
</div>
</div>
</ul>
</div>
</nav>
</body>
</html>
UserController:
#RestController
#RequestMapping("/users")
public class UserController {
#Autowired
private UserRepository urepo;
#RequestMapping("/")
public String index() {
return "index";
}
#RequestMapping("/userlogin")
public String index1(Model model) {
model.addAttribute("user", new User());
return "userlogin";
}
I was trying change #Controller to #RestController, putting my main class to up and so on, but i've got no result
I have two endpoints each of them is returning the "index.html" view.
http://localhost:8080/
this URL shows the index file and CSS is working as well. image
http://localhost:8080/product/1
this URL only shows the index file but CSS is not loading. image
MainController.java
package com.example.temporary.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class MainController {
#RequestMapping("/")
public String index() {
return "index";
}
#RequestMapping("/product/1")
public String process() {
return "index";
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head xmlns:th="http://www.thymeleaf.org">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" th:href="#{css/index.css}">
<title>Document</title>
</head>
<body>
<h1>Index Page</h1>
<a th:href="#{/product/1}">Click Me!</a>
</body>
</html>
index.css
* {
box-sizing: border-box;
}
body {
background-color: black;
color: white;
}
File Structure
image
try to include css as below in html
<link rel="stylesheet" th:href="#{/css/index.css}">
instead of css/index.css it should be /css/index.css
I couldn't achieve a functional reference scheme to my example application as follows. File teste.js seems not being reached by the resource declaration in jsp file. Any help could be valuable.
jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title> Composição </title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" charset="UTF-8" src="http://localhost:8080/compo/resources/js/teste.js"></script>
</head>
<body>
Greeting : ${greeting}
<table><tr><td id="save"> clique </td></tr></table>
<script type="text/javascript">
window.onload = function() {
document.getElementById("save").onclick = function fun() {
//alert("hello"); - working
testing("hello 2"); //not working
}
}
</script>
</body>
</html>
teste.js
function testing(message){
alert('messaged script: ' + message);
}
I am using Spring MVC and I've build the application in Eclipse, using its wizard, and for this reason it is using a "WebContent" folder structure, in spite of the fact that I have turn my project into a Maven project after creation. I think this is an important information.
UPDATE
After several tests, I concluded that the problem is in the Web-MVC configuration, because a similar project without Spring performs the access to resources perfectly.
Configuration (Spring 5.0.2):
package com.mycompany.compo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.mycompany.compo")
public class SpringConfiguration implements WebMvcConfigurer {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("public", "classpath:/resources/")
.setCachePeriod(31556926)
;
}
}
Hello I'm new in Thymeleaf and encountered a problem that might be trivial, but thymeleaf don't behave like it supposed to be. Just a little help will be much appreciated
I don't use spring boot for the matters of learning. Additionally, I am also pretty new to Spring. Might miss one or two things.
I have simple index.html like this
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Index 2</title>
</head>
<body>
<div th:replace="~{fragments/fragment1 :: fr1}"></div>
</body>
</html>
and fragment1.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
</head>
<body>
<div th:fragment="fr1"><h1>HERE IS FRAGMENTS 1</h1></div>
</body>
</html>
Supposedly it does resolve the template, but the result doesn't change at all.
here is what i get from the browser page source
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Index 2</title>
</head>
<body>
<div th:replace="~{fragments/fragment1 :: fr1}"></div>
</body>
</html>
and yes it exactly the same as raw index.html.
So I figured it might have something to do with the configuration, but it just looks fine for me. In my other learning project, it just works fine with the exactly same configuration.
Here is the configuration
/* package and imports */
#Configuration
#EnableWebMvc
#ComponentScan("com.eshop")
public class WebConfig extends WebMvcConfigurerAdapter {
private static final String UTF8 = "UTF-8";
private static final String VIEWS = "/WEB-INF/templates/";
private static final String RESOURCES_LOCATION = "/resources/";
private static final String RESOURCES_HANDLER = RESOURCES_LOCATION + "**";
//Thymeleaf Configuration
#Bean
public ITemplateResolver templateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setPrefix(VIEWS);
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
resolver.setCacheable(false);
return resolver;
}
#Bean
public SpringTemplateEngine templateEngine(){
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.setDialect(new SpringSecurityDialect());
return templateEngine;
}
#Bean
public ViewResolver viewResolver(){
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setCharacterEncoding(UTF8);
return viewResolver;
}
// tells DispatcherServlet to give static resources and not handle the resources itself
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
// handle various resources like javascript and css
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler( RESOURCES_HANDLER ).addResourceLocations( RESOURCES_LOCATION );
}
}
pom.xml
<!-- thymeleaf -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.0.RELEASE</version>
</dependency>
here is the project tree
webapp
|__resources
|__WEB-INF
|__i18n
|__templates
|__fragments
|__fragment1.html
|__index.html
What do I miss here and how can I fix this?
Try calling the th:replace without ~{}
<div th:replace="fragments/fragment1 :: fr1"></div>
Also make sure you have separate html file named fragment1.html
This Layouts tutorial should help you get going.
I am trying to use layouts/templates with Thymeleaf but I'm getting the following exception.
Exception processing template "user/index": Error resolving template "/layouts/default.html", template might not exist or might not be accessible by any of the configured Template Resolvers
Here is my ThymeleafConfig.java
#Configuration
public class ThymeleafConfig {
#Bean
public ServletContextTemplateResolver templateResolver() {
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".html");
resolver.setTemplateMode("HTML5");
resolver.setOrder(1);
return resolver;
}
#Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolver(templateResolver());
engine.addDialect(new LayoutDialect());
engine.addDialect(new SpringSecurityDialect());
engine.addDialect(new SpringStandardDialect());
return engine;
}
#Bean
public ThymeleafViewResolver thymeleafViewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
return resolver;
}
}
I have the following folder structure
webapp/
..WEB-INF/
....views/
......layouts/
........default.html
......user
........index.html
Here is my default.html which is my main layout.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Default</title>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<header>
This is a header from default.html
</header>
<section layout:fragment="content">
<p>Content should go here!</p>
</section>
<footer>
Footer from default
<p layout:fragment="custom-footer">Custom footer here!</p>
</footer>
<!-- scripts -->
<script src="https://code.jquery.com/jquery-2.1.3.min.js" />
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
</body>
</html>
Here is the index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="layouts/default.html">
<head>
<title>Users</title>
</head>
<body>
<section layout:fragment="content">
<p>This is a paragraph from content page 1</p>
</section>
<footer>
<p layout:fragment="custom-footer">This is some footer content from content page 1</p>
</footer>
</body>
</html>
They are in different folders but the pathing should work unless I'm just missing something really silly.
I found my issue. If you specify the suffix in your Thymeleaf config you do not need the .html extension.
#Bean
public ServletContextTemplateResolver templateResolver() {
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".html"); // here
resolver.setTemplateMode("HTML5");
resolver.setOrder(1);
return resolver;
}
It should be:
layout:decorator="layouts/default"
Instead of:
layout:decorator="layouts/default.html"
I'm guessing it was effectively looking for layouts/default.html.html which would be a problem.
I solved this issue by having following code:
#Configuration
public class ThymeleafConfig{
#Bean
public SpringTemplateEngine springTemplateEngine()
{
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(htmlTemplateResolver());
return templateEngine;
}
#Bean
public SpringResourceTemplateResolver htmlTemplateResolver()
{
SpringResourceTemplateResolver emailTemplateResolver = new SpringResourceTemplateResolver();
emailTemplateResolver.setPrefix("classpath:/templates/");
emailTemplateResolver.setSuffix(".html");
emailTemplateResolver.setTemplateMode(StandardTemplateModeHandlers.HTML5.getTemplateModeName());
emailTemplateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
return emailTemplateResolver;
}
}
The trick was to add: emailTemplateResolver.setPrefix("classpath:/templates/");
You should not give the extension.And you have to provide correct path like this
layout:decorator="../layouts/default"