如何使用变量设置包括值?

时间:2019-04-14 05:39:45

标签: thymeleaf

为简单起见,假设我们有一个模板html文件( test.htm ),如下所示:

arr2D = [[1 -1 -1]
         [-1 1 -1]
         [-1 -1 1]]

以下控制器用于返回test.htm:

<div th:fragment="test">
    this is a test fragment
</div>
<div th:include=":: test"> <!-- we'll change this line later -->
    this is a placeholder
</div>

在这种情况下,如果访问home索引,我们可以获得以下结果:

@Controller
public class HomeController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ModelAndView get(ModelAndView mav) {
        mav.setViewName("/test.htm");
        mav.addObject("fragmentName", ":: test"); // we'll use this later
        return mav;
    }
}

但是,如果我们使用变量this is a test fragment this is a test fragment 来设置th:include值,如下所示:

fragmentName

Thymeleaf抱怨此模板“ :: test”无法解析:

<div th:fragment="test">
    this is a test fragment
</div>
<div th:include="${fragmentName}"> <!-- modified to use a variable value -->
    this is a placeholder
</div>

这里是一个问题:有没有办法使用变量设置There was an unexpected error (type=Internal Server Error, status=500). Error resolving template [:: test], template might not exist or might not be accessible by any of the configured Template Resolvers (template: "/test.htm" - line 5, col 6) 值?

1 个答案:

答案 0 :(得分:1)

您可以使用Thymeleaf表达式预处理:

<div th:include="__${fragmentName}__"> 
    this is a placeholder
</div>

基本上,您指示thymeleaf首先对__ $ {fragmentName} __进行预处理,然后在解析值以在正常处理阶段使用它时,评估th:include就像是一个静态值th:include =“ :: test “