Last active
May 22, 2016 15:45
-
-
Save bufferings/d02661640c40ec3516760b961368368d to your computer and use it in GitHub Desktop.
Thymeleaf MyExpressionObject
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example; | |
import static org.hamcrest.CoreMatchers.is; | |
import static org.hamcrest.MatcherAssert.assertThat; | |
import java.util.Arrays; | |
import java.util.Collections; | |
import java.util.LinkedHashSet; | |
import java.util.Set; | |
import org.junit.Test; | |
import org.thymeleaf.TemplateEngine; | |
import org.thymeleaf.context.Context; | |
import org.thymeleaf.context.IExpressionContext; | |
import org.thymeleaf.dialect.IExpressionObjectDialect; | |
import org.thymeleaf.expression.IExpressionObjectFactory; | |
import org.thymeleaf.spring4.dialect.SpringStandardDialect; | |
public class ExpressionObjectTest { | |
public static class Yutori { | |
public String hello(String name) { | |
return "はろー" + name + "!ゆとりだよ!"; | |
} | |
} | |
@Test | |
public void canUseMyExpressionObject() { | |
TemplateEngine engine = new TemplateEngine(); | |
engine.setDialect(new SpringStandardDialect()); | |
engine.addDialect(new YutoriDialect()); | |
String result = engine.process("[[${#yutori.hello('しいば')}]]", new Context()); | |
assertThat(result, is("はろーしいば!ゆとりだよ!")); | |
} | |
public static class YutoriExpressionObjectFactory implements IExpressionObjectFactory { | |
private static final String YUTORI_EXPRESSION_OBJECT_NAME = "yutori"; | |
protected static final Set<String> ALL_EXPRESSION_OBJECT_NAMES = Collections | |
.unmodifiableSet(new LinkedHashSet<>(Arrays.asList(new String[] { YUTORI_EXPRESSION_OBJECT_NAME }))); | |
private static final Yutori YUTORI_EXPRESSION_OBJECT = new Yutori(); | |
@Override | |
public boolean isCacheable(String expressionObjectName) { | |
return true; | |
} | |
@Override | |
public Set<String> getAllExpressionObjectNames() { | |
return ALL_EXPRESSION_OBJECT_NAMES; | |
} | |
@Override | |
public Object buildObject(IExpressionContext context, String expressionObjectName) { | |
if (YUTORI_EXPRESSION_OBJECT_NAME.equals(expressionObjectName)) { | |
return YUTORI_EXPRESSION_OBJECT; | |
} | |
return null; | |
} | |
} | |
public static class YutoriDialect implements IExpressionObjectDialect { | |
private final IExpressionObjectFactory YUTORI_EXPRESSION_OBJECT_FACTORY = new YutoriExpressionObjectFactory(); | |
@Override | |
public String getName() { | |
return "YutoriDialect"; | |
} | |
@Override | |
public IExpressionObjectFactory getExpressionObjectFactory() { | |
return YUTORI_EXPRESSION_OBJECT_FACTORY; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment