Defining a template language
The first step in making a tool to pump out text from a template is to define the set of operations you'll allow within the template generator. Some useful actions are:
- Setting a variable
- Retrieving a variable
- Importing another file's content
- Prompting the user to fill in required variable's content
- Optionally performing an action based on a variable's content
- Allowing for inclusion of comments
- Indicating an action should be consise, so as to disrupt the text minimally.
- Indicating an action should use un-common escape characters, so that you're not constantly escaping normal text.
Thus I've found a language like the following suits my needs:
Normal text $v variable content to set$ $% variable_to_retrieve$ $? variable_to_optionally_retrieve$ $i file_to_import$The $ symbol works well because it's not very common for anything i'm normally generating text for. The single letter commands are easy to remember and use. Bracketing every command on both sides with the command symbol combined with simple space-separated fields makes for simple parsing of the text.
Implementing
Implementation of such a language is fairly simple.for each char 'ch' in input if ch is not $, output and continue find next $ create a substring advance 'ch' switch(first char of substring) case 'v': split substring by first space map first value to second value in a map case '%': lookup substring in a map output text throw if not found case '?': lookup substring in a map output text if not found case 'i': open file named by substring recurse
A full implemention of this is used to create this blog by pasting together headers and content to make every page have the same styling, and minimal external imports.
The code can be found on my github