嗨,有没有一种方法可以让我有一个基本的布局,比如节点的 express,see here ,什么时候用 mustache 做 Spring Boot ?所以我可以这样做:
基地布局:
<html>
<body>
<p>Title</p>
{{{body}}} // or similar, not sure about #
</html>
然后用Controller返回的 View 名作为内容渲染一个 View ,这样外面总是一样的?
最佳答案
您可以通过 Mustache lambda 函数执行此操作。通过本教程,我能够实现您所需要的:https://spring.io/blog/2016/11/21/the-joy-of-mustache-server-side-templates-for-the-jvm#layout-abstractions-using-a-lambda
创建一个这样的 Controller 建议:
@ControllerAdvice
class LayoutAdvice {
@ModelAttribute("layout")
public Mustache.Lambda layout() {
return new Layout();
}
}
class Layout implements Mustache.Lambda {
String body;
@Override
public void execute(Fragment frag, Writer out) throws IOException {
body = frag.execute();
}
}
这将使您的 Mustache 模板可以访问名为“layout”的 lambda 函数。 lambda 函数本身接收片段(它将在布局标签内,见下文)并将其存储在布局对象的
body
中。 field 。这可以从布局模板访问:<html>
<body>
{{{layout.body}}}
</body>
</html>
文件名必须是我们使用的“layout.html”
@ModelAttribute("layout")
以上。然后您可以通过调用 lambda 函数并传递一个片段来使用您的布局,该片段将成为您的布局主体:
{{#layout}}
<h1>Demo</h1>
<div>Hello World</div>
{{/layout}}
{{>layout}}
它将产生所需的输出:
<html>
<body>
<h1>Demo</h1>
<div>Hello World</div>
</body>
</html>
关于spring-boot - 如何在 mustache 中为 spring-boot 设置基本布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34111668/