对于那些希望在导入的宏前加上一些空格缩进的人,这里有一个执行工作的类:
public final static class IndentDirective
implements TemplateDirectiveModel
{
private static final String COUNT = "count";
public void execute(Environment environment, Map parameters, TemplateModel[] templateModels,
TemplateDirectiveBody body)
throws TemplateException, IOException
{
Integer count = null;
final Iterator iterator = parameters.entrySet().iterator();
while (iterator.hasNext())
{
final Map.Entry entry = (Map.Entry) iterator.next();
final String name = (String) entry.getKey();
final TemplateModel value = (TemplateModel) entry.getValue();
if (name.equals(COUNT) == true)
{
if (value instanceof TemplateNumberModel == false)
{
throw new TemplateModelException("The \"" + COUNT + "\" parameter " + "must be a number");
}
count = ((TemplateNumberModel) value).getAsNumber().intValue();
if (count < 0)
{
throw new TemplateModelException("The \"" + COUNT + "\" parameter " + "cannot be negative");
}
}
else
{
throw new TemplateModelException("Unsupported parameter '" + name + "'");
}
}
if (count == null)
{
throw new TemplateModelException("The required \"" + COUNT + "\" parameter" + "is missing");
}
final String indentation = StringUtils.repeat(' ', count);
final StringWriter writer = new StringWriter();
body.render(writer);
final String string = writer.toString();
final String lineFeed = "\n";
final boolean containsLineFeed = string.contains(lineFeed) == true;
final String[] tokens = string.split(lineFeed);
for (String token : tokens)
{
environment.getOut().write(indentation + token + (containsLineFeed == true ? lineFeed : ""));
}
}
}
您可以通过添加configuration.setSharedVariable("indent", new IndentDirective());
到 FreeMarker 配置来集成它,然后通过插入在模板中使用它
<@indent count=4>
[whathever template code, including macro usage]
</@indent>