【问题标题】:Implementing a lambda function with JMustache in java在java中用JMustache实现一个lambda函数
【发布时间】:2021-02-03 13:54:29
【问题描述】:

我正在关注 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 有什么作用?它被忽略了吗?是否有不同的引用写入片段内部?

【问题讨论】:

    标签: java javadoc mustache


    【解决方案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 方法的类。

    【讨论】:

    • 您仍然可以将new MyMustacheLambda() 替换为匿名类。您不必必须创建另一个类文件
    猜你喜欢
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 2022-12-05
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    相关资源
    最近更新 更多