Created
October 10, 2024 09:38
-
-
Save aschaeffer/c5f15d3f12933ac156a6308991eed378 to your computer and use it in GitHub Desktop.
Freemarker Example
This file contains hidden or 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 example; | |
| import freemarker.template.Template; | |
| import freemarker.template.TemplateException; | |
| import org.junit.jupiter.api.Test; | |
| import java.io.IOException; | |
| import java.io.Reader; | |
| import java.io.StringReader; | |
| import java.io.StringWriter; | |
| import java.util.HashMap; | |
| import java.util.Map; | |
| import java.util.Optional; | |
| import static org.junit.jupiter.api.Assertions.assertEquals; | |
| import static org.junit.jupiter.api.Assertions.assertTrue; | |
| public class FreemarkerTest { | |
| public static final String TEMPLATE_NAME = "HELLO_WORLD"; | |
| public Optional<String> hello(String name) { | |
| if (name == null) { | |
| return Optional.empty(); | |
| } | |
| String templateStr = "Hello, ${name}"; | |
| Reader reader = new StringReader(templateStr); | |
| StringWriter writer = new StringWriter(); | |
| Template template; | |
| try { | |
| template = new Template(TEMPLATE_NAME, reader); | |
| } catch (IOException e) { | |
| return Optional.empty(); | |
| } | |
| Map<String, Object> model = new HashMap<>(); | |
| model.put("name", name); | |
| try { | |
| template.process(model, writer); | |
| } catch (TemplateException e) { | |
| System.err.println(e.getMessage()); | |
| return Optional.empty(); | |
| } catch (IOException e) { | |
| System.err.println(e.getMessage()); | |
| return Optional.empty(); | |
| } | |
| return Optional.ofNullable(writer.toString()); | |
| } | |
| @Test | |
| void processTemplateTest() { | |
| assertTrue(hello(null).isEmpty()); | |
| assertTrue(hello("Fabian").isPresent()); | |
| assertEquals("Hello, World", hello("World").get()); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment