如何以编程方式将JS和CSS资源添加到< h:head> ;? [英] How to programmatically add JS and CSS resources to <h:head>?
问题描述
我需要以编程方式添加JS和CSS资源到JSF页面的< h:head>
。不清楚如何实现这一点。
I need to add programmatically JS and CSS resources to <h:head>
of JSF page. It isn't clear how to achieve this. Could someone give a hint or a kickoff example?
推荐答案
这取决于您要在哪里声明资源。通常 ,以编程方式声明它们的唯一原因是您有自定义 UIComponent
或 Renderer
,后者生成HTML代码,后者又需要这些JS和/或CSS资源。然后由 @ResourceDependency
或 @ResourceDependencies
。
That depends on where exactly you'd like to declare the resource. Normally, the only reason to programmatically declare them is that you've a custom UIComponent
or Renderer
which generates HTML code which in turn requires those JS and/or CSS resources. They are then to be declared by @ResourceDependency
or @ResourceDependencies
.
@ResourceDependency(library="mylibrary", name="foo.css")
public class FooComponentWithCSS extends UIComponentBase {
// ...
}
@ResourceDependencies({
@ResourceDependency(library="mylibrary", name="bar.css"),
@ResourceDependency(library="mylibrary", name="bar.js")
})
public class BarComponentWithCSSandJS extends UIComponentBase {
// ...
}
但如果你真的需要在其他地方声明它们,方法,在呈现响应之前调用 (否则太晚了),那么您可以通过 UIViewRoot#addComponentResource()
。组件资源必须创建为 UIOutput
的渲染器类型 javax.faces.resource.Script
或 javax.faces.resource.Stylesheet
分别表示完整< h:outputScript>
或< h:outputStylesheet>
。 库
和 name
属性只能放在属性映射中。
But if you really need to declare them elsewhere, such as in a backing bean method which is invoked before render response (otherwise it's simply too late), then you can do that by UIViewRoot#addComponentResource()
. The component resource must be created as an UIOutput
having a renderer type of javax.faces.resource.Script
or javax.faces.resource.Stylesheet
, to represent a fullworthy <h:outputScript>
or <h:outputStylesheet>
respectively. The library
and name
attributes can just be put in the attribute map.
UIOutput css = new UIOutput();
css.setRendererType("javax.faces.resource.Stylesheet");
css.getAttributes().put("library", "mylibrary");
css.getAttributes().put("name", "bar.css");
UIOutput js = new UIOutput();
js.setRendererType("javax.faces.resource.Script");
js.getAttributes().put("library", "mylibrary");
js.getAttributes().put("name", "bar.js");
FacesContext context = FacesContext.getCurrentInstance();
context.getViewRoot().addComponentResource(context, css, "head");
context.getViewRoot().addComponentResource(context, js, "head");
这篇关于如何以编程方式将JS和CSS资源添加到< h:head> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!