Search code examples
jsfjsf-2

Dynamic h:outputScript name attribute in ui:repeat


I'm using com.sun.faces version 2.1.18. I'm displaying a list of questions and for some questions (based on the database ID) I want to insert some dynamic Javascripts.

According to the h:outputScript tag specification the name attribute is of type: javax.el.ValueExpression (must evaluate to java.lang.String).

However, this code is working for me:

<ui:repeat value="#{js.questionScripts[question.id]}" var="script">
  <h:outputScript name="myScript.js" library="js" target="head"/>
</ui:repeat>

But this code isn't:

<ui:repeat value="#{js.questionScripts[question.id]}" var="script">
  <h:outputScript name="#{script}" library="js" target="head"/>
</ui:repeat>

The #{question} comes from a surrounding <ui:repeat> iteration over a list of questions.

I added an output to see if #{script} was not empty, but it contained the correct resource name.

Any ideas on how to solve this or implement an alternative?


Solution

  • The <h:outputScript> has to be created during view build time in order to be recognized by JSF resource management. The <ui:repeat> runs during view render time and is therefore too late. You have to use <c:forEach>. I'm not sure how it failed for you, but it works fine for me, provided that #{js} is a request, session or application scoped bean whose questionScripts property is already prepared during its (post)construction and that #{question.id} is available during view build time.

    <c:forEach items="#{js.questionScripts[question.id]}" var="script">
        <h:outputScript name="js/#{script}" target="head"/>
    </c:forEach>
    

    (note that you've to use items attribute instead of value attribute and also note that I fixed the seemingly improper usage of library attribute).

    See also: