当使用ui:composition模板时如何定制h:head?

14

我正在使用JSF来渲染一个HTML页面。我像这样设计页面:

<f:view xmlns="http://www.w3.org/1999/xhtml"
  xmlns:ui="http://java.sun.com/jsf/facelets"
  xmlns:p="http://primefaces.org/ui"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:f="http://java.sun.com/jsf/core">

<h:head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <meta name="language" content="fr" />
    <title><ui:insert name="title">My app</ui:insert></title>
</h:head>

<h:body>
    <div id="top">
        <ui:include src="/header.xhtml"/>
    </div>

    <h:panelGroup id="center" layout="block" >
        <ui:insert name="center"/>
    </h:panelGroup>

    <div id="bottom">
        <ui:include src="/footer.xhtml"/>
    </div>
</h:body>

这个模板有一些“客户端”页面,比如这个:

<ui:composition 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"
            xmlns:p="http://primefaces.org/ui"
            template="/layouts/master.xhtml">

<ui:define name="center">
    <ui:define name="title"><h:outputText value="#{myBean.description}"/></ui:define>
    <ui:include src="#{myBean.url}"/>
</ui:define>

在客户端,我需要在头部添加元信息。如果我们有像outputScript或outputStylesheet这样的标签,可以在文档的任何地方设置并在html“head”标签中呈现,那将非常棒。

我没有找到方法来实现这个功能。在这种情况下,是否有一种方法可以在头部添加标签? 谢谢!

1个回答

22

<h:outputStylesheet>标签会自动被移到<h:head>标签中,因此您不需要担心此问题。对于<h:outputScript>标签,默认情况下它会在声明的同一行呈现,您只需要将target属性设置为head,这样它也会自动被移动到<h:head>中。

<ui:define name="center">
    <h:outputStylesheet name="css/style.css" />
    <h:outputScript name="js/script.js" target="head" />
    ...
</ui:define>

对于其他 HTML 头部元信息,如果有必要,你可以声明另一个 <ui:insert>

<h:head>
    <ui:insert name="htmlhead" />
</h:head>

你可以按以下方式使用

<ui:define name="htmlhead">
    <meta ... />
</ui:define>

另请参见:


我正在使用JSF 2.1,但"h:outputStylesheet"或"h:outputScript"中并没有"target"属性。因此,第一种解决方案不起作用。 - Johnny
@Johnny:关于h:outputStylesheet你是对的,但是你似乎没有测试过h:outputScript。我已经更新了答案。 - BalusC
这种方式是否适用于组合组件,以便我们可以在ui:composition中定义它们,但它们将成为主模板中的头部的一部分? - hocikto
@hocikto:上面答案的第一段也适用于复合材料。另请参见例如https://dev59.com/wGjWa4cB1Zd3GeqPvOvP。 - BalusC
@BalusC 我需要在头部基本上呈现一些HTML(不是CSS,也不是JS),但只在网站的某些部分中,想知道如何处理。 - hocikto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接