Re: Import macros into global namespace
Daniel Dekany <[email protected]>
| Newsgroups | gmane.comp.web.freemarker.user |
|---|---|
| Message-ID | <[email protected]> |
Tuesday, February 8, 2011, 12:23:13 AM, Chris wrote:
>>> Is it possible to import a library of macros into the main namespace?
>>> We'd like to do this using Configuration.autoImport().
>>
>> Doesn't Configuration.setAutoIncludes do what you want?
>
> It doesn't, so far as I know. Neither
>
> conf.setAutoIncludes(null, "mylibrary.ftl")
>
> nor
>
> conf.setAutoIncludes("main", "mylibrary.ftl")
There is setAutoImports and then there is setAutoIncludes. What I'm
asking is if you have tried setAutoIncludes. That does the same as
#include (as opposed to #import).
> will put the macros in the main namespace. Is is possible to get them
> into that namespace?
>
>> Maybe this can be worked around if you import the
>> macro library with a non-conflicting name, then pass the macro library
>> (the hash that #import creates) back to the data-model through a
>> custom method of the a custom data-model root class, which then uses
>> that for fall-backs. I never tried to do this, so I'm not sure if it
>> has a catch...
>
> Sounds like it might work. How do I get access to the hash that #import
> creates? And where?
So this is only interesting if you want make all the stuff uniformly
accessible with that "mynamespace" perfix (as opposed to making them
uniformly accessible without any prefix - for that see the #include
trick earlier). Regarding how to achieve this, now that I think more
about it, I think the cleanest solution is this:
MySpecialTemplateHashModel mynamespace = new MySpecialTemplateHashModel(...);
root.put("mynamespace", mynamespace)
Environment env = myTemplate.createProcessingEnvironment(root, out);
mynamespace.setDefaults(env.importLib("/include/mymacros.ftl", "iDontCare"))
env.process(); // and only then process the template
Here you will have a "mynamespace" variable in the data-model that
contains whatever you have put into MySpecialTemplateHashModel; that's
trivial so far. The trick is that MySpecialTemplateHashModel has a
setDefaults(TemplateHashModel) method, that sets a fall-back
TemplateHashModel. Above I set it to the namespace hash that <#import
"/include/mymacros.ftl" as iDontCare> would create in FTL. This way
the two hashes don't hide each other (since "mynamespace" and
"iDontCare" are different names), instead they are merged under the
"mynamespace" name. I haven't tried this... but I'm certain this
approach will work.
--
Best regards,
Daniel Dekany
------------------------------------------------------------------------------
The ultimate all-in-one performance toolkit: Intel(R) Parallel Studio XE:
Pinpoint memory and threading errors before they happen.
Find and fix more than 250 security defects in the development cycle.
Locate bottlenecks in serial and parallel code that limit performance.
http://p.sf.net/sfu/intel-dev2devfeb