Ryan
Ryan

Reputation: 24035

How to inject HTML into {0} of springMessageText in Velocity?

I'm using Apache Velocity in an internationalized Spring MVC website.

I want to use "Redirecting in X seconds" as the phrase (message key) that my translators will translate. The X will obviously be a variable number of seconds, and Javascript will update the page every second to count it down.

I thought I'd do this:

#springMessageText("Redirecting in {0} seconds" ["<span class='seconds'>5</span>"])

But this displays:

Redirecting in <span class='seconds'>5</span> seconds

(without parsing the HTML).

I need to be able to put the HTML tag in there because that is how javascript will know which part of the translated phrase to update.

What am I doing wrong?

Upvotes: 0

Views: 1993

Answers (1)

Ryan
Ryan

Reputation: 24035

UPDATED ANSWER:

I created a custom macro file called custom.vm:

#macro( springMessageHtml $code, $args, $defaultValue)
    $springMacroRequestContext.getMessage($code, $args.toArray(), $defaultValue, false)
#end

In my velocity.properties file, I changed this line to reference it: velocimacro.library=org/springframework/web/servlet/view/velocity/spring.vm,/velocity/custom.vm

And now in my views (like sample.vm), I can call it like: #springMessageHtml("Redirecting in {0} seconds" ["<span class='seconds'>5</span>"])

OLDER ANSWER:

I found an answer here: http://feima2011.wordpress.com/2011/01/18/misc-notes/

#set($args = ["<span class='seconds'>5</span>"])
            $springMacroRequestContext.getMessage("Redirecting in {0} seconds",     
$args.toArray(), "", false)

#springMessageText is just a macro that calls $springMacroRequestContext.getMessage() anyway; by calling it directly, I'm able to specify that last parameter (a boolean for whether to escape the HTML).

Now I'm able to have unescaped HTML. Maybe eventually I'll code a new macro called #springMessageHtml, and it will call $springMacroRequestContext.getMessage() with the escapeHtml parameter set to False. Then in my view, I'd only need 1 line of code.

Upvotes: 2

Related Questions