tags:

views:

237

answers:

3

I've got this, which is working:

<c:choose>
    <c:when test="${sometest}">
        Hello, world!
    </c:when>
    <c:otherwise>
        <fmt:message key="${page.title}" />
    </c:otherwise>
</c:choose>

And I want to change it to this:

<c:choose>
    <c:when test="${sometest}">
        <c:set var="somevar" scope="page" value="Hello, world!"/>
    </c:when>
    <c:otherwise>
        <c:set var="somevar" scope="page" value="<fmt:message key="${page.title}">"
    </c:otherwise>
</c:choose

But of course the following line ain't correct:

<c:set var="somevar" scope="page" value="<fmt:message key="${page.title}">"

How can I assign to the somevar variable the string resulting from a call to fmt:message?

+2  A: 

It is also possible to specify the value to set using the contents of the body, rather than through the value attribute:

<c:set var="somevar" scope="page">
  <fmt:message key="${page.title}"/>
</c:set>
Timo Westkämper
@Timo Westkämper: +1, thx
NoozNooz42
+4  A: 

The fmt:message has a var attribute as well which does effectively what you want.

 <fmt:message key="${page.title}" var="somevar" />

That's all. Bookmark the JSTL tlddoc, it may come in handy.

BalusC
@BalusC: thanks to you again... Interestingly there are three answers and three differents way to do it :)
NoozNooz42
You're welcome. The other two answers are technically the same and does indeed effectively the same. It's only more code and only proves that the presence and the use of the `var` attribtue in the majority of the JSTL `fmt` tags is relatively unknown ;)
BalusC
Why is it called `fmt:message` if all it's doing is setting a variable. Is it formatting or modifying the variable in any way?
Lotus Notes
@Byron: Because it by default displays the message associated with the key when you omit the `var` attribute.
BalusC
+1  A: 

You'll have to do with:

<c:set var="title"><fmt:message key="${page.title}"></c:set>
<c:set var="somevar" scope="page" value="${title}" />

Since you can't use <fmt:message .. /> on that spot is my experience, has to do with nesting like you suggested. Or go with @balusc suggestion ;-)

André van Toly
André van Toly: +1, thx to you too... I went with the shorter var attribute of the fmt tag that BalusC pointed out.
NoozNooz42