用 Facelets 进行模板化

模板化和重用的第一步是创建一个模板。

一个网页通常由一些基本的部分组成:header, body,footer。用Facelets,你能把这些通用的元素放在一个单独的页面里,并创建一个带有可编辑区的模板,如下面的模板所示:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
<head>     
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />      <title>Sample Template</title> 
</head>  
<body> <h1>#{title}</h1>      
<div><ui:insert name="menu"/></div>      
<p><ui:insert name="body"/></p>    
</body>  
</html>

对于menubody来说,<ui:insert/> 标签用来标记这块地方的内容会根据每一页变化。你可以用这个模板来创建其他的页面,并给menubody区域提供不同的内容。

<ui:composition template="template.xhtml">         
<ui:param name="title" value="Here's my Title"/>         
<ui:define name="menu">Here's My Menu</ui:define>         
<ui:define name="body">Here's My Body</ui:define>        
</ui:composition>     

这个例子介绍了另外一个标签<ui:composition/>。该标签提供了一对特征。它删掉了它外面的任何内容,就是说,你可以写一些普通的HTML页面,而Facelets将只是用或者 显示出现在<ui:composition/>标签里面的内容。

为了把内容和模板配对,<ui:define/>标签的name属性和模板中的<ui:insert/>标签的name属性一致的就可以替换。为了简便地传递变量或者文字,你可以使用<ui:param/>标签,该标签把其value属性作为模板中的一个变量来替代。

使用Includes

页面中的位置这个概念在页面中定义可重用的内容是相当强大的。上面几个例子展示了如何使用模板中的位置来显示内容。但是如果你想从另一个页面中包含进来一些东西该如何做呢?用<ui:include/>标签:

<!-- include.xhtml -->      ...      <span id="leftNav">       
<ui:include src="/WEB-INF/siteNav.xhtml"/>     </span>      ...
<!-- siteNav.xhtml -->      ..     
 <ui:composition>     <!-- myfaces tomahawk components -->       
<t:tree2 value="#{backingBean.options}" var="opt">       ...        </t:tree2>     </ui:composition>      ...

Facelets处理include.xhtml时,siteNav.xhtml的所有<ui:composition/>中的内容将被包含进include.xhtml

<!-- include.xhtml -->      ...    
<span id="leftNav">      <!-- myfaces tomahawk components -->     
 <t:tree2 value="#{backingBean.options}" var="opt">       ...       </t:tree2>    </span>    ...

如果你愿意给siteNav.xhtml传递变量,这些变量供tree组件使用,那么你可以使用<ui:param/>标签:

<!-- include.xhtml -->      ...    <span id="leftNav">      
 <ui:include src="/WEB-INF/siteNav.xhtml">       
<ui:param name="menuBean" value="#{backingBean.options}"/>       
</ui:include>    </span>   ...
<!-- siteNav.xhtml -->      ...      
<ui:composition>       <!-- myfaces tomahawk components -->       
<t:tree2 value="#{menuBean}" var="opt">       ...       
</t:tree2>      </ui:composition>      ...

你能够看到现在siteNav.xhtml可以使用变量menuBean并且menuBean是通过<ui:include/>标签来传递的。

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值