如何在另一个中嵌入一个DropWizard(带有freemarker)视图?

我正在使用DropWizard和Freemarker构建一个视图,该视图根据Web服务的结果显示不同类型的表单。

我已经将表单创建为视图 – 每个都有自己的ftl。

所以,在我的资源中,我发现我需要哪种forms,然后加载main.ftl,将表单视图作为参数传递(见下文)。

这不起作用。 谁能看到我们哪里出错? 或者使用DropWizard和freemarker将视图链接在一起有一种完全不同的方式吗?

@GET public Form getForm() { FormView view = new FormView(service.getForm()); return new MainView(view); } public class FormView extends View { private final Form form; public FormView(Form form) { super("formView.ftl"); this.form = form; } public Form getForm() { return form; } } public class MainView extends View { private final FormView formView; public MainView(FormView formView) { super("main.ftl"); this.formView = formView; } public FormView getFormView() { return formView; } } public class TextForm extends View implements Form { private int maxLength; private String text; public TextForm(int maxLength, String text) { super("textForm.ftl"); this.maxLength = maxLength; this.text = text; } public int getMaxLength() { return maxLength; } public String getText() { return text; } } main.ftl     // This evaluates to formView.ftl, but it seems to create a new instance, and doesn't have the reference to textForm.ftl. How do we reference a dropwizard view here?   formView.ftl  ${form?html} // also tried #include form.templateName textForm.ftl  
${text?html}

根据讨论,我认为你需要这样的东西:

 <#-- main.ftl -->   <#include formView.templateName>   

formView.templateName必须求值为textForm.ftlnumberForm.ftlcomplexForm.ftl或您可能拥有的任何表单视图。 不需要在这些文件之间选择的中间文件。 我认为你遇到了问题,因为FormView.getTemplateName()返回一个硬编码的formView.ftl 。 我认为您需要的是此方法返回包含您要显示的表单类型的实际模板文件的名称。

我已经想出了如何做到这一点。

您创建了一个扩展ViewTemplateView类(见下文)。
然后,所有的View类都需要扩展TemplateView

构造函数接受一个额外的参数,即“body”模板文件,它是进入模板内部的主体。

然后,在模板文件中,执行类似的操作。

   

My template file

<#include body>
footer etc

TemplateView类。

 public abstract class TemplateView extends View { private final String body; protected TemplateView(String layout, String body) { super(layout); this.body = resolveName(body); } public String getBody() { return body; } private String resolveName(String templateName) { if (templateName.startsWith("/")) { return templateName; } final String packagePath = getClass().getPackage().getName().replace('.', '/'); return String.format("/%s/%s", packagePath, templateName); } } 

希望这有助于某人。