Wicket - 添加body标签属性

时间:2011-10-27 20:05:05

标签: wicket

我被困 -

我需要让Wicket Panel能够将一个类属性添加到< body>它所在的任何页面的标记。 用法示例:

爪哇:

add(new SpecialSidebarComponent("sidebar"));

生成的HTML:

<body class="sidebar">
   ...
   <div id="sidebar">My Wicket Panel</div>
   ...
</body>

我无法添加一个wicket:id并将body作为Wicket组件,因为这使得在我拥有的大页面层次结构中向组件添加组件非常困难,而且它仍然不容易允许Panel修改body属性。

我认为BodyTagAttributeModifier可能是为了这个,但显然它是用于其他东西并且无法让它起作用(Wicket: how to use the BodyTagAttributeModifier class?

有用的想法吗?

更新

在查看它时,BodyTagAttributeModifier类似乎只是 用于Panel的父标记,而不是Page的&lt; body&gt;标记:

示例(Scala语法):

class Home extends WebPage {
  add(new Sidebar("sidebar"))
}
class Sidebar(id: String) extends Panel(id) {
  add(new BodyTagAttributeModifier("class", true, new Model("layout-class"), getParent))
}

模板:

<html>
<body>
    <div wicket:id="sidebar">Sidebar</div>
</body>
</html>

渲染:

<html>
<body>
    <div class="layout-class">
        <h1>Hello World!</h1>
    </div>
</body>
</html>

非常令人困惑的名字恕我直言。不解决问题,但至少更有意义。

3 个答案:

答案 0 :(得分:3)

我个人认为Javascript选项对于这个特定情况来说是最干净的。但是,您对add(Component...)最终的评论让我相信您可能对setTransparentResolver(true)方法感兴趣。这是它的工作原理......

BasePage.html

<body wicket:id="body">
    <div wicket:id="panel" />
</body>

BasePage.java

public class BasePage extends Page {

    public String bodyClass = "";

    public BasePage() {
       super();
       WebMarkupContainer bodyContainer = new WebMarkupContainer("body");
       bodyContainer.setTransparentResolver(true);
       bodyContainer.add(new SimpleAttributeModifier("class", new PropertyModel<String>(this, "bodyClass")));
    }
}

MyPage.java(扩展BasePage)

public class MyPage extends BasePage {

    public MyPage() {
        super();
        add(new SidebarPanel("panel"));
        super.bodyClass = "sidebar";
    }
}

即使您没有将SidebarPanel直接添加到BasePage中的bodyContainer,它仍然会因setTransparentResolver(true)而失效。

对于您的简单案例,请使用Javascript。对于因子类无法适应容器而受到约束的一般问题,请注意透明解析。

答案 1 :(得分:2)

如果你真的不能给<body>标签一个wicket:id(我假设你没有一个BasePage,每个或几乎每一个其他页面都延伸到其中来抽象),在页面渲染时(在呈现<body>标记时)不可能知道要附加到哪个类,它将被简单地从HTML复制到输出。

然而,你可以通过javascript实现相同的目标。制作Panel工具IHeaderContributor并使用IHeaderResponse.renderOnDomReadyJavscript()

public abstract class SpecialSidebarComponent(String id) extends Panel 
                 implements IHeaderContributor {
    .....
    public void renderHead(IHeaderResponse response){
        String javascript = "document.body.setAttribute('class', 'sidebar');";
        response.renderOnDomReadyJavascript(javascript);
    }
    ....
}

答案 2 :(得分:0)

我认为你使用BodyTagAttributeModifier是正确的,至少根据JavaDoc。链接文章中的编译问题源于使用不存在的构造函数...

在SpecialSidebarComponent中你应该能够做到这一点:

add(new BodyTagAttributeModifier("class", Model.of("sidebar"), this));

现在不能尝试这个,因为我不在我的开发计算机上......