Skip to content

Instantly share code, notes, and snippets.

@jbrains
Created October 15, 2018 16:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbrains/64e12aa12f89c78da840ada7e314f1ec to your computer and use it in GitHub Desktop.
Save jbrains/64e12aa12f89c78da840ada7e314f1ec to your computer and use it in GitHub Desktop.
Why do we do this? Why isn't it easier just to create a template in memory and merge it with data in memory?
package ca.jbrains.org.freemarker;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.vavr.collection.HashMap;
import io.vavr.collection.Map;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import static org.hamcrest.CoreMatchers.is;
// CONTRACT
// Merge placeholders with a data-model.
// The data-model is a tree of values with keys. Reach down
// the tree with keys separated by dots: a.b.c means c inside b inside a.
//
// ${key} turns into the value corresponding to the key 'key'.
//
// ${key!"default value"} uses a default value in case the data-model
// contains no value (or a `null` value) for the key 'key'.
//
// We can implement the data-model as a Map or as a hierarchy of Java beans,
// or as a mixture of the two: a Map with a value that's a Java bean, and so on.
//
//
public class LearnToMergeAFreemarkerTemplateTest {
// The Freemarker documentation tells me to treat this like a Singleton,
// so I'm doing exactly that by instantiating just one of these and using
// it for every test.
public static final Configuration standardConfigurationForTesting = new Configuration(Configuration.VERSION_2_3_28);
@Test
public void oneSimplePlaceholder() throws Exception {
String result = mergeTemplate(
"Hello, ${name}.",
HashMap.of("name", "J. B."));
Assert.assertThat(result, is("Hello, J. B.."));
}
private String mergeTemplate(String templateText, Map<String, String> dataModel) throws TemplateException, IOException {
return mergeTemplateWithDataModel(
createTemplateInMemory(
"anonymous template", templateText),
dataModel.toJavaMap());
}
private static Template createTemplateInMemory(String name, String templateText) throws IOException {
return new Template(name,
new StringReader(templateText),
standardConfigurationForTesting);
}
private String mergeTemplateWithDataModel(Template oneSimplePlaceholder, java.util.Map<String, String> dataModel) throws TemplateException, IOException {
StringWriter canvas = new StringWriter();
oneSimplePlaceholder.process(dataModel, canvas);
return canvas.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment