使用 JMustache 在 Java 中实现一个 lambda 函数。

huangapple go评论73阅读模式
英文:

Implementing a lambda function with JMustache in java

问题

我正在遵循 JMustache 的文档:https://github.com/samskivert/jmustache。文档中提到我们可以调用 Java 函数并在 Mustache 模板中使用它们。我有一个类似这样的 lambda 函数:

 Mustache.Lambda lookupInstance = new Mustache.Lambda() {
      public void execute (Template.Fragment frag, Writer out) throws IOException {
          out.write("<b>");
          frag.execute(out);
          out.write("</b>");
      }
    };

然后,我有一个模板文件,其中引用了这个 lambda,如下所示:

{{#myMethod}} is awesome.{{/myMethod}}

模板的输出结果如下:

is awesome.

我预期的是:

<b> is awesome.</b>

有人可以帮我弄清楚为什么方法没有正常执行吗?我已经尝试了相当长时间来调试这个问题。奇怪的是,任何写入 Writer 的内容都会被忽略,而 frag.execute 则是唯一起作用的部分。这个方法对 Writer 做了什么?它被忽略了吗?在 frag 内部有一个不同的写入引用吗?

英文:

I am following the documentation for JMustache: https://github.com/samskivert/jmustache. It says that we can call java functions and use them in Mustache templates. I have a lambda function like so

 Mustache.Lambda lookupInstance = new Mustache.Lambda() {
      public void execute (Template.Fragment frag, Writer out) throws IOException {
          out.write("<b>");
          frag.execute(out);
          out.write("</b>");
      }
    };

Then I have a template file that references the lambda like so

{{#myMethod}} is awesome.{{/myMethod}}

The output from the template is the following:

is awesome.

I was expecting

<b> is awesome.</b>

Can someone please help me figure out why the method isn't executing properly? I've been trying to debug this for quite some time now.It's odd that anything written to the Writer is ignored and that the frag.execute is the only thing working. What does that method do with the Writer? Is it ignored? Is there a different reference to write to inside of the frag?

答案1

得分: 1

我遇到的问题是,Spring RestDocs使用Mustache作为一种传递依赖关系。我已经将JMustache添加到了pom.xml中,这是多余的。我们可以通过以下方式使用lambda函数:

@Override
public void document(Operation operation) throws IOException {
    try {
        RestDocumentationContext context = (RestDocumentationContext) operation
            .getAttributes().get(RestDocumentationContext.class.getName());

        StandardWriterResolver writerResolver = new StandardWriterResolver(
            new RestDocumentationContextPlaceholderResolverFactory(),
            "UTF-8",
            new TemplateFormat() {
                @Override public String getId() { return outFileExt; }
                @Override public String getFileExtension() { return outFileExt; }
            });

        Map<String,Object> data = new HashMap<>(operation.getAttributes());
        data.put("myMethod", new MyMustacheLambda());

        TemplateEngine templateEngine =
            (TemplateEngine) data
            .get(TemplateEngine.class.getName());

        try (Writer writer = writerResolver.resolve(
            operation.getName(),
            outFileName,
            context)) {
            writer.append(templateEngine
                    .compileTemplate(this.templateName)
                    .render(data));
        }

    } catch (Throwable t) {
        t.printStackTrace();
    }
}

然后通过以下方式实现lambda函数:

import java.io.IOException;
import java.io.Writer;
import org.springframework.restdocs.mustache.Mustache.Lambda;
import org.springframework.restdocs.mustache.Template.Fragment;

public class MyMustacheLambda implements Lambda {
  
    @Override
    public void execute(Fragment fragment, Writer writer) throws IOException {
        String output = fragment.execute();
        writer.write("test");
    }

}

因此,我们需要创建一个实现Lambda接口并覆盖execute方法的类。

英文:

The issue that I was running into was that Spring RestDocs uses Mustache as a transitive dependency. I had added JMustache to the pom.xml which was redundant. We can use a lambda function via the following

@Override
  public void document(Operation operation) throws IOException {
    try {
    RestDocumentationContext context = (RestDocumentationContext) operation
        .getAttributes().get(RestDocumentationContext.class.getName());

    StandardWriterResolver writerResolver = new StandardWriterResolver(
        new RestDocumentationContextPlaceholderResolverFactory(),
        &quot;UTF-8&quot;,
        new TemplateFormat() {
          @Override public String getId() { return outFileExt; }
          @Override public String getFileExtension() { return outFileExt; }
        });
   
    Map&lt;String,Object&gt; data = new HashMap&lt;&gt;(operation.getAttributes());
    data.put(&quot;myMethod&quot;, new MyMustacheLambda());
    
    
    TemplateEngine templateEngine = 
        (TemplateEngine) data
        .get(TemplateEngine.class.getName());


    try (Writer writer = writerResolver.resolve(
        operation.getName(), 
        outFileName,
        context)) {
      writer.append(templateEngine
              .compileTemplate(this.templateName)
              .render(data));
    }
    
    }
    catch (Throwable t) {
      t.printStackTrace();
    }
  }

and implement the lambda function via

import java.io.IOException;
import java.io.Writer;
import org.springframework.restdocs.mustache.Mustache.Lambda;
import org.springframework.restdocs.mustache.Template.Fragment;

public class MyMustacheLambda implements Lambda {
  
  @Override
  public void execute(Fragment fragment, Writer writer) throws IOException {
      String output = fragment.execute();
      writer.write(&quot;test&quot;);
  }

}

So we have to create a class that implements Lambda and overrides the execute method.

huangapple
  • 本文由 发表于 2020年10月21日 01:14:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/64450208.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定