Re: Java constants in Freemarker template

Daniel Dekany <[email protected]>
Newsgroups gmane.comp.web.freemarker.user
Message-ID <[email protected]>
Saturday, March 29, 2008, 3:16:14 PM, Sunil wrote:

> Hi,
> Iam developing a portlet application in which Freemarker templates we are
> using for View.
>
> Iam trying to use the constants present in Java class file in the freemarker
> templates. I have the read the posts which says that we can use java constants
> in the Freemarker templates by using the following commands.
>
> ${stack.findValue("@fully.classified.classname@constantName")}

That may works like that under a sepcific Web Application Framework
(Struts, I guess), but not in general.

> But, When Iam trying to access the constants in my template file using the
> above command, Iam getting the below freemarker exception.
>
> freemarker.core.InvalidReferenceException: Expression stack in undefined.
>
> can any one please let me know whats wrong here and how can we access 
> constants present in Java class/Interface file in the Freemarker template file.

So, the thing is that the Web Application Framework + the application
specific Controller parts has full control over what's visible in the
data-model, thus the static constants of Java classes will not be
there automatically; someone has to put it there. An easy way is
putting the result of yourBeansWrapper.getStaticModels() into the
data-model (or to make that object accessible by other means, like
with an FTL library). If you put it into the data-model with "statics"
name (just an example), then you could write this in the template:
${statics[fully.classified.classname].constantName}. Also, you can
expose the static entries of only a single class if you put the result
of BeansWrapper.getStaticModels().get("fully.classified.classname")
into the data-model. With a similar trick you can expose JDK5 enums as
well, with yourBeansWrapper.getEnumModels().

Note 1: yourBeansWrapper should be just the ObjectWrapper that the
freemarker.tempalte.Configuration object uses. If you can't access
that, you can still use BeansWrapper.getDefaultInstance() for this
purpose.

Note 2: You can easily add something to all data-models at once by
using yourConfiguration.setSharedVariable(name, value) during
application initialization.

> Thanks,
> Sunil.


-- 
Best regards,
 Daniel Dekany


-------------------------------------------------------------------------
Check out the new SourceForge.net Marketplace.
It's the best place to buy or sell services for
just about anything Open Source.
http://ad.doubleclick.net/clk;164216239;13503038;w?http://sf.net/marketplace
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.