How can I embed one DropWizard (with freemarker) View in another one?

淺唱寂寞╮ 提交于 2019-12-06 10:08:22

Based on the discussion, I think you need something like this:

<#-- main.ftl -->
<html>
<body>
    <#include formView.templateName>
</body>
</html>

formView.templateName must evaluate to textForm.ftl, numberForm.ftl, complexForm.ftl or whatever form view you might have. There's no need for an intermediate file that chooses between these. I think you are running into problems because FormView.getTemplateName() is returning a hard-coded formView.ftl. I think that what you need is for this method to return the name of the actual template file containing the form type you want to display.

I've figured out how to do this.

You make a TemplateView class (see below) that extends View.
Then all your View classes need to extend TemplateView instead.

The constructor takes an extra parameter, the "body" template file, that is the body to go inside the template.

Then, inside your template file, do something like this.

<html>
  <body>
      <h1>My template file</h1>
          <#include body>
      <footer>footer etc</footer>
  </body>
</html>

The TemplateView class.

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);
    }
}

Hope this helps someone.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!