package org.ambraproject.wombat.freemarker;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateScalarModel;
import org.ambraproject.wombat.controller.SiteResolver;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.Map;

/**
 * Formats a path, relative to the root of a site, into an absolute link.
 */
public class SiteLinkDirective implements TemplateDirectiveModel {

  @Autowired
  private SiteResolver siteResolver;

  @Override
  public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
      throws TemplateException, IOException {
    Object pathObj = params.get("path");
    if (!(pathObj instanceof TemplateScalarModel)) {
      throw new RuntimeException("path parameter required");
    }
    String path = ((TemplateScalarModel) pathObj).getAsString();
    String link = new SitePageContext(siteResolver, env).buildLink(path);
    env.getOut().write(link);
  }

}

@@ -255,32 +255,83 @@
 .TemplateModel;%0A
+import freemarker.template.TemplateModelException;%0A
 import freemarke
@@ -358,24 +358,24 @@
 calarModel;%0A
-
 import org.a
@@ -611,16 +611,543 @@
 e link.%0A
+ * %3Cp/%3E%0A * If there is no loop var, render the link as the output of the macro. For example:%0A * %3Cpre%3E%0A *   %3Clink rel=%22stylesheet%22 type=%22text/css%22 href=%22%3C@siteLink path=%22resource/css/screen.css%22 /%3E%22/%3E%0A * %3C/pre%3E%0A * The directive may be invoked with one loop var, in which case the directive will assign the link to that variable and%0A * render the body with it. For example:%0A * %3Cpre%3E%0A *   %3C@siteLink path=%22resource/css/screen.css%22 ; link%3E%0A *     %3Clink rel=%22stylesheet%22 type=%22text/css%22 href=%22$%7Blink%7D%22/%3E%0A *   %3C/@siteLink%3E%0A * %3C/pre%3E%0A
  */%0Apubl
@@ -1728,37 +1728,313 @@
 h);%0A
-    env.getOut().write(link);
+%0A    if (loopVars.length == 0) %7B%0A      env.getOut().write(link);%0A    %7D else if (loopVars.length == 1) %7B%0A      loopVars%5B0%5D = env.getObjectWrapper().wrap(link);%0A      body.render(env.getOut());%0A    %7D else %7B%0A      throw new TemplateModelException(%22SiteLinkDirective does not take more than 1 loopVar%22);%0A    %7D
 %0A  %7D

Add mode to SiteLinkDirective for assigning link to loopvar