#thymeleaf
#thymeleaf
Вопрос:
Чтобы упростить это, давайте предположим, что у нас есть html-файл шаблона (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>
И следующий контроллер используется для возврата test.htm:
@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
Но если мы используем переменную fragmentName
для установки значения th:include следующим образом:
<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>
Thymeleaf жалуется, что этот шаблон «:: test» не может быть разрешен:
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)
Здесь возникает вопрос: есть ли способ установить th:include
значение с помощью переменной?
Ответ №1:
Вы можете использовать предварительную обработку выражения Thymeleaf:
<div th:include="__${fragmentName}__">
this is a placeholder
</div>
По сути, вы поручили thymeleaf сначала выполнить предварительную обработку __${fragmentName}__ и после разрешения значения использовать его на обычной фазе обработки при вычислении th:include, как если бы это было статическое значение th:include=»:: test»
Комментарии:
1. спасибо, это работает как шарм! еще раз спасибо за помощь.