【问题标题】:Include template for Springboot/Thymeleaf application包含 Spring Boot/Thymeleaf 应用程序的模板
【发布时间】:2023-03-22 14:25:01
【问题描述】:

索引控制器:

@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 中,当我们点击一​​个新链接时,我们希望在模板的一部分中替换掉一个简单的包含函数:

<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 的等价物是什么?

【问题讨论】:

    标签: java spring-boot thymeleaf templating


    【解决方案1】:

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

    您必须使用控制器将可在表达式中使用的对象放入 (Spring) 模型中。我的猜测是它应该可以工作,你会做类似的事情

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

    它应该可以工作

    【讨论】:

    • 你提供的''my-template'参数有什么作用?
    • 这个值应该插入到
    • 我明白你的意思,但是这个值应该总是不同的,具体取决于用户点击的 url。我的一个链接看起来像这样,例如&lt;a href="#" th:href="@{/request}"&gt;Make a Request&lt;/a&gt;。它应该加载 index.html 并将内容 div 替换为 request.html 片段。
    • 是的,但您可以在控制器中控制它,例如model.addAttribute("template", determineTheNameOfTheTemplate(request))
    • 你是说我应该传递一个新函数来检查“模板”参数的名称,该参数根据它分配新视图吗?
    猜你喜欢
    • 2015-09-14
    • 2016-01-26
    • 2021-12-14
    • 2021-03-03
    • 1970-01-01
    • 2019-10-31
    • 2020-11-16
    • 2019-04-11
    • 2020-03-14
    相关资源
    最近更新 更多