gpt4 book ai didi

java - FreeMarker:使用宏时保持标识

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:48:48 25 4
gpt4 key购买 nike

我正在使用 FreeMarker 模板引擎从 Web 服务的抽象描述中生成一些 PHP 类。我的问题是,当我在 FreeMarker 模板中调用宏时,宏会在宏调用之前插入没有左侧空格的文本。

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>

这将生成如下内容:

<?php
class foo {
/*
* foo
* bar foo, bla
*/

$a;
$b;
}
?>

一个解决方案是,将前导空格作为参数提交给宏,但这只会使模板更难读。有更好的解决方案吗?

最佳答案

docAsComment 似乎总是在代码生成中以相同的缩进级别调用。您可以将该缩进烘焙到宏中。

如果注释的缩进是可变的,则必须传入缩进级别。我不明白您关于使模板更难阅读的评论。它确实使宏更复杂一些。

调用看起来像这样:

<@docAsComment class.doc 1/>

宏会变成这样:

<#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>

还不错,真的。您可以通过缩进使宏更易于阅读:

<#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>

关于java - FreeMarker:使用宏时保持标识,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15658872/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com