Reputation: 123
I have the following record definition:
-record(contact, {name, email})
Assuming that I have a few contacts in the mnesia database already and I want to render them with erlydtl on an html page, I first query the database:
F = fun() -> qlc:e(qlc:q([X || X <- mnesia:table(contact)])) end,
{atomic, Contacts} = mnesia:transaction(F).
Having my contacts stored in the Contacts variable, and having a contacts.html file, I try to render it so (the below code is happening inside a misultin callback):
erlydtl:compile("contacts.html", contacts),
contacts:render(Contacts).
The contacts.html file is as following:
{% for contact in contacts %}
{{ contact.name }}
{{ contact.email }}
{% endfor %}
The above obviously does not work. Help!
Thank you.
-
Upvotes: 3
Views: 743
Reputation: 36
mochiweb_util provides record_to_proplist/2
and record_to_proplist/3
which work nicely. These are also dynamic with regards to the records you pass in.
Upvotes: 2
Reputation: 30985
I hope a nicer solution exists, but you could define an helper function like:
contact_to_list(C) ->
lists:zip(record_info(fields, contact), tl(tuple_to_list(C))).
And pass that to ErlyDTL:
your_template:render([{contact, contact_to_list(C)}]).
UPDATE: If you want to make this 'dynamic', so that you can pass a variable instead of an atom to the record_info, you can use the 'exprecs' parse transform:
http://doc.erlagner.org/parse_trans/exprecs.html
Basically, after you add the parse_trans app as a dependency, you can add the following to your module:
-compile({parse_transform, exprecs}).
-export_records([
contact
]).
And then have your new dynamic function:
record_to_list(Rec, RecName) ->
lists:zip('#info-'(RecName), tl(tuple_to_list(Rec))).
Upvotes: 3