code-template-tool
code-template-tool copied to clipboard
Subtemplates
This pull request adds support for generating SubTemplates.
The primary goal of subTemplates is to support lists of identical items within a template. Like a list of fields, args, or props. Multiple subTemplates can be defined for the same variable so the user can enter the variables once and have them applied in different ways throughout their templates. This results in a lists of lists output.
Use Cases:
- Creating a React class template. We can have a
props
variable with two subTemplates: one to place them in a PropTypes definition, and one to place them in a destructured list in the render function. The user will only need to type out a list of props likefirstName, image, addressStr
as a variable and they can get :
...
class ___ComponentName___ extends React.Component {
static propTypes = {
___propTypeFieldDefs___
}
render(){
const {___propsInline___} = this.props;
...
BECOMES
....
class Profile extends React.Component {
static propTypes = {
firstName: PropTypes. ,
image: PropTypes. ,
addressStr: PropTypes. ,
}
render(){
const {firstName, image, addressStr} = this.props;
....
I added a new folder called examples
that has an example of this working in it.
Technical Implementation Notes:
Variables have a new property: subTemplates
.
variables with subTemplates are parsed as lists IE - firstName, image, addressStr
When generated the subTemplate config will be applied against every entry in the list:
firstName
, image
, addressStr
SubTemplates are an array and each subTemplate has file, as, variableAlias, joinChars
;
file
- The name of the file located in the subTemplates
folder. IE - propTypeField.js
as
- The name of the variable this specific subTemplate will be installed at. IE - propTypeFieldDefs
variableAlias
- The variable name in the subTemplate file that will be replaced with the value from the list. IE - propName
joinChars
- The characters to use to join the results of all iterations. IE - \r\n
or ,
VariableTable has a second list called _aliases that takes each subTemplate as
property and aliases it to the variable. This list is used to lookup variable names that should be processed as subTemplates.
When generating files we take two passes now: First to process subTemplates and second to process non-subTemplates. This lets us use any other variable name inside our subTemplates.