Prolog is a powerful templating engine; I use M4, T4 and StringTemplate, but I find it much more gratifying to use Prolog for code generation, because it is declarative and grammar-based.
Suppose you want to generate a list, e.g. [1 2]:
ns([]) –> [].
ns([N|Rest]) –> N, ” “, ns(Rest).
l(Ns) –> “[“, ns(Ns), “]”.
:- phrase(l([“1”, “2”]), S), format(“~s\n”, [S]).
The output is [1 2 ].
Maybe your data are in a database:
db(“1”). db(“2″).
ns([]) –> [].
ns([N|Rest]) –> N, ” “, ns(Rest).
l(Ns) –> “[“, ns(Ns), “]”.
:- bagof(N, db(N), Ns), phrase(l(Ns), S), format(“~s\n”, [S]).
Again, the output is [1 2 ].
This is the reverse process of parsing; we generate something based on the data in the Prolog fact database using DCGs. Even so, code generation is based on a formal grammar definition, instead of manual flow control.
A real-world example of this approach is the html_write library.