包含Springboot / Thymeleaf应用程序的模板

时间:2017-02-07 10:37:35

标签: java spring-boot thymeleaf templating

索引控制器:

@Controller
public class IndexController {

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

    @Autowired
    UsersRepository usersRepository;

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

MVC配置:

@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");
    }

}

在PHP中,当我们点击新链接时,我们想要换出的模板部分有一个简单的include函数:

<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"); 
} 

在我的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>

Springboot / Thymeleaf的等价物是什么?

1 个答案:

答案 0 :(得分:1)

查看http://www.thymeleaf.org/doc/articles/layouts.html

您必须使用控制器将表达式中可以使用的对象放入(Spring)模型中。我的猜测是,它应该有用,你可以做像

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

它应该有用