Please note that this list was retired:
https://freemarker.apache.org/mailing-lists.html

Thus, I cross-post this to the current list,
[email protected].


Friday, November 30, 2018, 9:25:25 PM, sjkelleyjr wrote:

> I'm trying to validate a template given a JSON structure.  By this I mean,
> given a template with fields to read from a JSON file, and the JSON file,
> I'd like to ensure all of the fields expected in the template are present in
> the JSON file.  A programmatic version of this would be perfect (with an
> error message, rather than an empty template if the JSON property doesn't
> exist):

What do you mean by "rather than an empty template"? Templates fail on
runtime if they refer to a missing variable (unless a default was
specified, like ${missing!'N/A'}). So, one approach is just to run the
template and see if it fails. Of course it's not an option in many
use-cases, so read on.

> https://try.freemarker.apache.org/
>
>
> Is there an existing solution to this, or is this something I'll have to
> write myself?  If it is something I'll have to write myself, and suggestions
> on how to proceed with this task?

The best you can do is getting the Template object (which is an
already parsed template), and walk the AST (Abstract Syntax Tree) to
figure out what variables are referenced. This is not a published API,
and is awkward at places, with misnomers at places... but, it's by far
the best option. You can see it in action, used to convert to FM3
language, here:
https://github.com/apache/freemarker/tree/3/freemarker-converter

A problem is that the AST API is not published, means, in theory it
has no backward compatibility guarantees. But I can tell that in
practice, it's very, very unlikely to break in FreeMarker 2.x (and 3.x
is totally incompatible anyway).

Another problem is that because of the dynamic nature of the template
language, extracting such information reliably is only possible for
simple templates. That's because you can miss referred variables
inside macro/function defined in other templates, inside custom
TemplateDirectiveModel calls, inside ?eval-ed strings, referred via
.var[dynamicName], etc. Also you can have false alarms at referring to
variables that are created inside the template, if you are not carful.

-- 
Thanks,
 Daniel Dekany

Reply via email to