发布于2026-07-22 阅读(0)
扫一扫,手机访问
Sitemesh 默认提供了一些常用的规则,但实际开发中,我们往往需要自定义规则来满足更灵活的需求。比如,想把页面中的某个特定区块提取出来,放到母版页的指定位置——这时候,就得自己动手写 TagRule 了。

其实思路很简单:定义一个规则,解析像 这样的标签,把里面的内容提取出来,存到页面属性里,然后在母版页中用 输出就行。下面直接看代码。
/** * Extracts the contents of any elements that look like *and write the contents * to a page property (page.foo). * *... This is a cheap and cheerful mechanism for embedding multiple components in a * page that can be used in different places in decorators.
* * @author Joe Walnes */ public class ContentBlockExtractingRule extends BasicBlockRule{ private final ContentProperty propertyToExport; public ContentBlockExtractingRule(ContentProperty propertyToExport) { this.propertyToExport = propertyToExport; } @Override protected String processStart(Tag tag) throws IOException { tagProcessorContext.pushBuffer(); return tag.getAttributeValue("tag", false); } @Override protected void processEnd(Tag tag, String tagId) throws IOException { propertyToExport.getChild(tagId).setValue(tagProcessorContext.currentBufferContents()); tagProcessorContext.popBuffer(); } }
有了这个规则,接下来只需要把它注册到 TagRuleBundle 里。修改 ScriptTagRuleBundle 中的 install 方法,把 ContentBlockExtractingRule 加进去即可。
public class ScriptTagRuleBundle implements TagRuleBundle {
@Override
public void install(State defaultState, ContentProperty contentProperty, SiteMeshContext siteMeshContext) {
defaultState.addRule("content", new ContentBlockExtractingRule(contentProperty.getChild("page")));
}
@Override
public void cleanUp(State defaultState, ContentProperty contentProperty, SiteMeshContext siteMeshContext) {
}
}
用法非常直观:在页面中使用 包裹需要提取的内容,比如引入一些 JS 文件:
然后在母版页中,用 把它放到你需要的位置,比如 的末尾:
这样一来,JS 文件就能被灵活地插入到任意位置,不再受限于页面本身的顺序。不过,这个方案虽然简单,也存在一些需要注意的地方。
最大的问题在于:每增加一个新的 content 区块,都需要去母版页里添加对应的 标签。这就像 ASP.NET 的母版页一样,母版页本身需要预留位置。另外,上面的代码中 propertyToExport.getChild(tagId).setValue(...) 是直接覆盖的,如果同一个 tagId 在多个地方使用,后面的内容会覆盖前面的,导致丢失。
Sitemesh 本身没有提供直接拼接多个相同 tag 内容的规则。如果确实需要把多个区块的内容合并到同一个位置(比如都追加到页面末尾),可以考虑自己实现一个 TagRule,在 processEnd 时使用 append 方式,而不是直接 setValue。这样就能累加内容,最终输出所有片段。
以上就是关于 Sitemesh 中通过自定义 TagRule 实现内容块提取的完整思路和代码示例。实际项目中可以根据需要灵活调整,比如处理多个同名 tag 的拼接、支持嵌套等扩展。希望对你有所帮助。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8