简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM