如何以编程方式将 JS 和 CSS 资源添加到 <h:head> [英] How to programmatically add JS and CSS resources to <h:head>

查看:20
本文介绍了如何以编程方式将 JS 和 CSS 资源添加到 <h:head>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以编程方式将 JavaScript 和 CSS 资源添加到 JSF 页面的 .目前尚不清楚如何实现这一目标.我该怎么做,或者是否有启动示例?

I need to add programmatically JavaScript and CSS resources to <h:head> of a JSF page. It isn't clear how to achieve this. How can I do it or is there a kickoff example?

推荐答案

这取决于您希望在哪里声明资源.通常,以编程方式声明它们的唯一原因是您有一个自定义的UIComponentRenderer 生成 HTML 代码,而 HTML 代码又需要那些 JS 和/或 CSS 资源.然后由 @ResourceDependency<声明它们/code>@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 {
    // ...
}

但是如果您真的需要在其他地方声明它们,例如在渲染响应之前调用的支持 bean 方法中(否则为时已​​晚),那么您可以通过 UIViewRoot#addComponentResource().组件资源必须创建为 UIOutput 具有 javax.faces.resource.Scriptjavax.faces.resource.Stylesheet 的渲染器类型,以表示完整的 <h:outputScript> 分别.libraryname 属性可以放在属性映射中.

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 资源添加到 &lt;h:head&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆