2

I'm trying to implement an advanced selectOneMenu (PrimeFaces) to choose a locale based on its flag icon. The icons are shown in the list but not for the selected item (the same happens on showcase). How could I do this?

<p:selectOneMenu id="mySOMId" value="#{localeBean.locale}" var="mySOMVar" converter="#{localeConverter}" >
    <f:selectItems 
        value="#{myBean.locales}" 
        var="localeSIVar"
        itemLabel="#{localeSIVar.language}" 
        itemValue="#{localeSIVar}" />
    <p:column style="text-align: center;" >
        <h:graphicImage library="default" height="20" name="img/#{mySOMVar.language}.svg" />
    </p:column>
</p:selectOneMenu>

I can see that f:selectItems has an itemLabelEscaped attribute, which I could use to output <img> tag in itemLabel, but I don't know what I would put on its src.

Thanks

2
  • Does putting a static image from somewhere work? I would not expect it to include html. Did you try?
    – Kukeltje
    Jun 17, 2020 at 20:32
  • @Kukeltje do you mean inside itemLabel? If so, yes, I just tried putting the following there, and it worked. itemLabel="&lt;img src='https://someurl/icon.png' height='20' /&gt;"
    – reidestis
    Jun 17, 2020 at 20:40

1 Answer 1

5

You can use the #{resource['library:name']} syntax to print an URL for the resource, as indicated in How to reference CSS / JS / image resource in Facelets template?

So, given that you actually wanted to use a

<h:graphicImage library="default" height="20" name="img/#{localeSIVar.language}.svg" />

within the itemLabel, and that itemLabelEscaped attribute of <f:selectItems> is set to true, then you can use the following syntax as value of itemLabel:

itemLabel="&lt;img height='20' src='#{resource['default:img/' += localeSIVar.language += '.svg']}' /&gt;"

Notes:

  • You can only use plain HTML there, not JSF components.
  • For improved readability, better use single quotes as attribute value separators within the plain HTML which is in turn declared as an attribute surrounded by double quotes. You can of course also use &quot; instead of these single quotes.
  • The single quotes continue to work fine in EL expression as shown above, no need for re-escaping. You can even use double quotes within the EL expression, but syntax highlighting in code editors is prone to fail here, potentially causing unnecessary confusion.
  • The += operator is new since EL 3.0; in case you're still using an older EL version, head to How to concatenate a String in EL? for alternate ways to concatenate a string in EL (and then reusing it as a variable).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.