I can never decide wether to host code stuff on my code blog (that is very inactive and no-one reads) or here where someone might see it. I like this little tidbit so I’ll post it here.

For whatever reason that we don’t need to get in to here I will probably need to create dynamic LaTeX documents in the near future. That is, pull in a bunch of figures from a database and put them into a LaTeX table. I will do all the number-cruching and stuff with Clojure so I wanted to keep my solution as much in Clojure as possible.

I started looking around at Java templating engines but they were all very Java’y and I don’t really like Java. Then I found Fleet which is a general purpose templating engine written entirely in Clojure, well-written at that.

The documentation leaves a little to be desired but from the generous amounts of tests and various tidbits of documentation on the Github page I managed to figure out how to use it. I’ll try to explain a bit of how to use fleet and give an example.

If you like me just want to template one file all you need is the fleet command. However the fleet command returns something called a partial, I didn’t know what that was but managed to figure it out. Basically you give (fleet) three arguments, the first one is a vector of variables that you want to use in your template, the second is the template string; if you have a template in a file you have to use something like (slurp) first to put it in a string. The third argument is just what kind of escaping you want, for LaTeX I just put it on bypass since it’s not important.

But here’s the thing, the partial that (fleet) returns is a function expecting the arguments that you gave in the first vector to the (fleet) command. My LaTeX template example:

So after running the (fleet) command with [number] as the first argument, I run the function (partial) returned by (fleet) with the argument of a number. Now this number is used in the template where I have used <(str number)>:

I just took the standard LaTeX template and put in the Fleet templating engine’s syntax for clojure interpolation.

When I now run the partial with the argument that I told it to take; It returns the interpolated template as a string. I then spit that string to a file and run a shell command to turn it into a PDF. And voilá, dynamically generated PDF’s that are fast and consistent.


tetris