Text and Code Generation with Matlab
See MTemplate for the full tutorial and download.This toolbox allows you to write hybrid text/matlab functions. This means you write text and embed matlab commands in the text to generate code, html, xml or any other general or specialized text formatted file.
For example the below file usecase1.mt
#% Example template. #% #% t = mtemplate_compile('mtemplate_usecase1.mt'); #% t(3) # function usecase1(rows) <html> <body> # for i = 1:rows <tr><td>GEN_DATA = <%=gendata%></td></tr> <%=genline(i)%> # end </body> </html> # function gendata <%= i %> # end #end # function genline(row) <tr> #for e = 1:10 <td> <%= e %> </td> #end </tr> # end
when compiled and run as
t = mtemplate_compile('mtemplate_usecase1.mt'); t(3)
will generate
<html>
<body>
<tr><td>GEN_DATA = 1 </td></tr>
<tr>
<td> 1 </td>
<td> 2 </td>
<td> 3 </td>
<td> 4 </td>
<td> 5 </td>
<td> 6 </td>
<td> 7 </td>
<td> 8 </td>
<td> 9 </td>
<td> 10 </td>
</tr>
<tr><td>GEN_DATA = 2 </td></tr>
<tr>
<td> 1 </td>
<td> 2 </td>
<td> 3 </td>
<td> 4 </td>
<td> 5 </td>
<td> 6 </td>
<td> 7 </td>
<td> 8 </td>
<td> 9 </td>
<td> 10 </td>
</tr>
<tr><td>GEN_DATA = 3 </td></tr>
<tr>
<td> 1 </td>
<td> 2 </td>
<td> 3 </td>
<td> 4 </td>
<td> 5 </td>
<td> 6 </td>
<td> 7 </td>
<td> 8 </td>
<td> 9 </td>
<td> 10 </td>
</tr>
</body>
</html>
It is also possible to generate XML / XHTML using the XML markup helper.
#% Example template. #% #% This template uses the XML builder "xmlt" #% #% t = mtemplate_compile('mtemplate_usecase3.mt'); #% t() #?CWS # function mtemplate_usecase3 # x = xmlt; #= x.html #= x.head <%= x.title('Hi There') %> #end #= x.body <%= x.h1('Heading 1') %> #= x.div('class', 'main_text') Here is a #= x.a('href', 'http://xtargets.com') link #end to my homepage #end #= x.div('class', 'table_div') #= x.table #= foreach(1:3) @(r) #= x.tr #= foreach(1:3) @(c) #= x.td <%= r + c %> #end #end #end #end #end #end #end #end # end
generates
<html> <head><title>Hi There</title></head> <body> <h1>Heading 1</h1> <div class = "main_text"> Here is a <a href="http://xtargets.com">link</a> to my homepage </div> <div class = "table_div"> <table> <tr> <td>2 </td> <td>3 </td> <td>4 </td> </tr> <tr> <td>3 </td> <td>4 </td> <td>5 </td> </tr> <tr> <td>4 </td> <td>5 </td> <td>6 </td> </tr> </table> </div> </body> </html>
Goto downloads area