I want to create a template file in java and Im using Eclipse IDE. I want to create a template file such that one program which gets the parameters from the users, it should be able to paste these parameters into the template file and then save it as a separate file. How can I do this ?
Please guide me.
Thanks N.B
Here's how you would do this in my open-sourced template engine, Chunk.
import com.x5.template.Theme;
import com.x5.template.Chunk;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
...
public void writeTemplatedFile() throws IOException
{
Theme theme = new Theme();
Chunk chunk = theme.makeChunk("my_template", "txt");
// replace static values below with user input
chunk.set("name", "Lancelot");
chunk.set("favorite_color", "blue");
String outfilePath = getFilePath();
File file = new File(outfilePath);
FileWriter out = new FileWriter(file);
chunk.render(out);
out.flush();
out.close();
}
my_template.txt (simply place in the classpath in themes/my_template.txt)
My name is {$name}.
My favorite color is {$favorite_color}.
Output:
My name is Lancelot.
My favorite color is blue.
Your template can be made a bit smarter by adding |filters and :defaults to your tags.
my_template.txt - example 2
My name is {$name|defang:[not provided]}.
My favorite color is {$favorite_color|defang|lc:[not provided]}.
In this example, the defang filter removes any characters that might help form an XSS attack. The lc filter changes the text to lowercase. And anything after the colon will be output in case the value is null.
There is an Eclipse plugin available for editing Chunk templates directly in the Eclipse IDE. The plugin provides syntax highlighting and an outline view for template documents.
Chunk can do a lot more, take a peek at the docs for a quick tour. Full disclosure: I love Chunk in part because I created it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With