A class similar to MGffTemplate
is used in IDLdoc to produce all its output. When I changed from a bunch of print statements scattered over various methods of a class to templates where all the output is in a template file, it was a <em>lot</em> easier to focus on the content of the output. If you need to generate text-based reports (HTML, XML, LaTeX, DocBook, etc.) from IDL, I would suggest using this class.
The files needed to use the template are the MGffTemplate
class (docs) and the MGffTokenizer
class (docs).
Let’s take a look at a simple example. In this example, mg_template_example.pro
(docs) will use the template file image-file.tt
to produce this output (source code of output). The code in mg_template_example
queries an image file and gets a structure, info
.
filename = filepath('people.jpg', subdir=['examples', 'data'])
result = query_image(filename, info)
Then it simply creates a template from the template file, passes the info
structure and the name of output file to the process
method, and frees the template object.
otemplate = obj_new('MGffTemplate', 'image-file.tt')
otemplate->process, info, 'image.html'
obj_destroy, otemplate
This is easy, the real work for doing output is now in the template file. The template file is just a text file, most of which will be copied verbatim into the output. But there are directives enclosed in [%
and %]
that pass commands to the template object. Output in the directives will be processed in some way (depending on the directive) and then included in the output. The simplest directive simply inserts a variable into the output. For example,
Number of bands[% channels %]
Here channels
was a field of the info
structure passed into the process
method. Also, any IDL expression that returns a string (or can be converted to a string) can be used, like
Dimensions[% strjoin(strtrim(dimensions, 2), ', ') %]
where dimensions
was a field of the info
structure.
There are other directives for FOR
loops, IF
statements, and several ways to include other files. More on these features later; I hoping to create a more complicated example that uses some of these features soon.
February 12th, 2007 at 11:45 pm
[…] Templates are tools for creating text output reports. The beauty of templates is that they allow a separation of the code that generates/calculates information from the code that produces the output. The template code produces the output and is done in plain text in the type of output desired with a few directives that are used to insert the real information, check conditions, do loops, include other files, etc. This article will demonstrate more features than my original post about templates. The demo program mg_report_demo.pro (docs) uses three templates to create its output: the main template, the header, and the footer. […]
January 31st, 2008 at 11:40 am
[…] these previous posts about the template class. […]
October 25th, 2010 at 5:15 pm
Thank you,
very very useful!!