Martin Erlic
Martin Erlic

Reputation: 5667

Include template for Springboot/Thymeleaf application

Index Controller:

@Controller
public class IndexController {

    private static final Logger log = LoggerFactory.getLogger(TmtApplication.class);

    @Autowired
    UsersRepository usersRepository;

    @RequestMapping("/index")
    String index(){
        return "index";
    }
}

MVC Config:

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("home");
        registry.addViewController("/").setViewName("home");
        registry.addViewController("/index").setViewName("index");
        registry.addViewController("/login").setViewName("login");
        registry.addViewController("/request").setViewName("index");
        registry.addViewController("/requests").setViewName("index");
        registry.addViewController("/team").setViewName("index");
    }

}

In PHP, we have a simple include function in the part of the template we want to swap out when we click on a new link:

<a href="index.php?action=notifications">notifications</a>

    if (!empty($_GET['action'])) { 
    $action = $_GET['action']; 
    $action = basename($action); 
    if (file_exists("templates/$action.htm") 
        $action = "index"; 
    include("templates/$action.htm"); 
} else { 
    include("templates/index.htm"); 
} 

On my index.html:

<body>

<div class="container" style="width: 100% !important;">

    <div th:replace="fragments/header :: header"></div>

    // Include dynamic content here depending on which menu item was clicked
    <div th:replace="@{'fragments/' + ${template}} :: ${template}"></div>

    <div th:replace="fragments/footer :: footer"></div>

</div>

</body>

What's the equivalent for Springboot/Thymeleaf?

Upvotes: 0

Views: 1019

Answers (1)

thopaw
thopaw

Reputation: 4054

Have a look at http://www.thymeleaf.org/doc/articles/layouts.html

You have to put the objects you can use in expressions into the (Spring) model with your controller. My guess is that it should work, wenn you do somthing like

@RequestMapping("/index")
String index(ModelMap model){
    model.addAttribute("template", "my-template")
    return "index";
}

it should work

Upvotes: 1

Related Questions