Introduction
Previously in my Simplified Web Development with JSON and the Twig Ternary Operator, I had used JSON that had boolean values. Recently, I created another form that has a survey with checkboxes and I stored the JSON with string
values instead. This article gives an alternate example of using the Twig ternary operator to handle string
s.
The JSON Code
My survey JSON sample looks like the following example:
In the above JSON, the keys represent the survey questions, and the string
values represent the checkbox that was chosen. In the above case, “strong_A
” means “Strong Agree”, and “some_D
” means “Somewhat Disagree”. It’s just a simpler way to write/code the JSON and still keep it understandable.
I struggled for a long time on how to handle processing of the JSON data in my Twig template when presenting a view of the form that was submitted. I show the results of the submitted form in an HTML table with a table row for each question and the selected checkbox
es. So one row consists of the question + checkbox1
+ checkbox2
+ checkbox3
+ checkbox4
, and a total of 4 questions. So to do this in Twig, I struggle with how to create the for
loop.
I thought maybe I could do a Twig for
loop using {% for i in 0..3 %}
to process each of the 4 checkbox
es, and thus I was thinking of using the following JSON code:
So in the above, I would store each checkbox
as a boolean in the JSON array, however, this would actually require a lot more Twig code, and a lot of if
/else
statements. I wanted to simplify my code and reduce the number of lines required.
Problems with Twig If Statements
One way of processing whether any of the checkbox
es is selected is by using if
/else
statements, however, the code gets messy and looks something like the following code sample:
Notice each HTML td
element has an if
/else
statement, and a total of 32 lines are used for one table row. This is a lot of code.
Simplifying the Code with the Twig Ternary Operator
I simplified the code by using the Twig ternary operator (as described in the documentation) to replace all the if
/else
statements. For example, to check my JSON in Twig to see if the “Strongly Agree” checkbox is selected, I use the following code in my HTML td
element:
Where in the above “(survey[‘Recommend’] == ‘strong_A’)
” does a comparison to see if it matches the string
, and if so, then show a checked checkbox
. The code is an HTML escape code to render a checked checkbox
. The code is an empty checkbox
.
Example in Twigfiddle
I created a Twigfiddle here to show you the twig working in case you need to see it in action. Also, you will need to see the result in HTML, so there's a twig fiddle showing the resultant rendered HTML in this SyncFiddle.
Enjoy!