将元包含到 JSF

Include meta to JSF

我有一个 JSF 页面,其中包含另一个页面的 <head>...</head>。基本上是这样的:

<ui:include src="/path/head.xhtml"/>
<h:body>
...
</h:body>

我想为每个使用 <ui:include src="/path/head.xhtml"/> 的页面添加独特的 <meta name="description" content="Unique content">。 我有两个想法:

  1. 我可以将 <meta name="description".../> 放到首页并在包含页面上覆盖它吗?
  2. 或者我可以用某种方式将这个 <meta.../> 从包含页面放到头部?

几种方式:

  1. 在没有 name 的情况下使用 <ui:insert> 并让 <ui:include> 的主体覆盖它:

    /WEB-INF/includes/head.xhtml

    <h:head>
        ...
        <ui:insert>
            <meta name="description" content="Default description" />
        </ui:insert>
        ...
    </h:head>
    

    /page.xhtml

    <ui:include src="/WEB-INF/includes/head.xhtml">
        <meta name="description" content="Overridden description" />
    </ui:include>
    
  2. 使用 <ui:insert>name,并使用 <ui:decorate><ui:define> 而不是 <ui:include>:

    /WEB-INF/includes/head.xhtml

    <h:head>
        ...
        <ui:insert name="description">
            <meta name="description" content="Default description" />
        </ui:insert>
        ...
    </h:head>
    

    /page.xhtml

    <ui:decorate template="/WEB-INF/includes/head.xhtml">
        <ui:define name="description">
            <meta name="description" content="Overridden description" />
        </ui:define>
    </ui:decorate>
    
  3. 当您已有默认描述时,只需将 <ui:param> 与元内容一起使用即可保持代码干爽:

    /WEB-INF/includes/head.xhtml

    <h:head>
        ...
        <meta name="description" content="#{empty description ? 'Default description' : description}" />
        ...
    </h:head>
    

    /page.xhtml

    <ui:include src="/WEB-INF/includes/head.xhtml">
        <ui:param name="description" value="Overridden description" />
    </ui:include>
    

另请参阅:

  • How to include another XHTML in XHTML using JSF 2.0 Facelets?
  • Which XHTML files do I need to put in /WEB-INF and which not?