I am building a web app that basically consists of several selects, couple of checkboxes, and one input text field. Each select contains more than 4 options. After a user selects their options, fills out the text input, checks off any possible checkboxes, and presses Submit, a template text is generated in a textarea. The generated text is basically a template that uses all of the options specified by the user. In a simple form, it could go something like this:
- User selects “blue” and “hello” from selects, does not check any checkboxes, and writes “John” in the input text field.
- The text that is then generated is:
Hello, John, you have a blue car.
Now, the above example is about 100 times less complex than what my generated text is actually like. And here comes the question: what is the best way to code this? Currently, I opted for the ugly nested switch statements with a lot of static text and loads of IF statements. There is a limit to it though because if I add more complexity, I’m hitting the limit of extending the current switch statements and also wanting to avoid creating another level of switch statements.
Is the best way to just generate all possible variation of the text (I’m guessing there is at least a 200-250 and simply run through a single switch statement that return a selected template (this however makes applying changes to one word/sentence/etc. a nightmare)? Or should I abstract all the choices and build the final text with just variables (e.g. using above example: $greeting, $name, $middle $color $object.)? What are the best practices for generating text?
This is not specific to JavaScript but that is what I’m using so suggestions for how to do it in JS would be welcome. Thanks for your help!
One way to do this is to have a data model using JSON. Your UI updates the values in the data model, then you output the whole thing after every change. This way you can skip a lot of the logic.
jQuery templating can help make this work: