i'm using the FreeMarker template engine to generate some php classes from an abstract description of a webservice. My problem is, when i call a macro in a FreeMarker template, the macro inserts the text without the lefthand whitespace before the macro call.
exampleTemplate.ftl:
<?php
class ${class.name} {
<@docAsComment class.doc/>
<#list class.fields as field>
$${field.name};
</#list>
<#-- ... -->
}
?>
<#macro docAsComment doc>
/*
<#if doc.title != "">
* ${doc.title}
</#if>
<#list doc.content as content>
<#if content != ""> * ${content}</#if>
</#list>
*/
</#macro>
This will generate something like this:
<?php
class foo {
/*
* foo
* bar foo, bla
*/
$a;
$b;
}
?>
One solution would be, to submit the leading whitespace as an argument to the macro, but that makes the template only more unreadable. Is there a better solution?
It would seem that docAsComment
is always invoked at the same level of indentation in the code generate. You could bake that indentation into the macro.
If the indentation of the comment is variable, you'd have to pass in the indentation level. I don't understand your comment about that making the template harder to read. It does make the macro a little more complicated.
The invocation would look like this:
<@docAsComment class.doc 1/>
Macro would change to something like this:
<#macro docAsComment doc indent=1>
<#local spc>${""?left_pad(indent * 4)}</#local>
${spc}/*
<#if doc.title != "">
${spc}* ${doc.title}
</#if>
<#list doc.content as content>
<#if content != "">${spc} * ${content}</#if>
</#list>
${spc}*/
</#macro>
Not too bad, really. You can make the macro a little easier to read by indenting it:
<#macro docAsComment doc indent=1>
<#local spc>${""?left_pad(indent * 4)}</#local>
${spc}/*<#lt>
<#if doc.title != "">
${spc}* ${doc.title}<#lt>
</#if>
<#list doc.content as content>
<#if content != "">${spc} * ${content}</#if><#lt>
</#list>
${spc}*/<#lt>
</#macro>