Twine Version: 2.10.0
I would like to conditionally open and close divs from within if statements within a for loop. Here’s a simplification of the code I’m using:
<<for _a to 0; _a lt 4; _a++>>
<<if _a == 0>>
<div class="col1">
<</if>>
<<if _a == 1>>
<div class="col2">
<</if>>
<<if _a == 2>>
<div class="col3">
<</if>>
<<if _a == 3>>
<div class="col4">
<</if>>
You are player _a
</div>
<</for>>
This code prints the closing div tags as text and then says it can’t find the closing tags for the divs. Is there any way I can fix this problem?
svlin
2
You could try something like this:
<<for _a to 0; _a lt 4; _a++>>
<<if _a == 0>>
<<set _class = "col1">>
<<elseif _a == 1>>
<<set _class = "col2">>
<<elseif _a == 2>>
<<set _class = "col3">>
<<elseif _a == 3>>
<<set _class = "col4">>
<</if>>
<div @class=_class>You are player _a</div>
<</for>>
Instead of opening the <div>
, it sets a variable with the desired class, then uses the evaluation directive to add the class to the <div>
.
In this specific case, it might also be easier to do something like this:
<<for _a to 0; _a lt 4; _a++>>
<<set _class = "col"+String(_a+1)>>
<div @class=_class>You are player _a</div>
<</for>>
1 Like
Thank you! That worked great, but I have a follow-up question.
I’d like to present the results in a tables, with two results in each row, like this:
<table>
<tr>
<td>You are player 1</td>
<td>You are player 2</td>
</tr>
<tr>
<td>You are player 3</td>
<td>You are player 4</td>
</tr>
</table>
I can’t see a way to achieve this using your technique. Is there a way to adapt it to give this result?
svlin
4
Try this:
<<set _table = "<table>">>
<<set _column = 0>>
<<for _a to 0; _a lt 4; _a++>>
<<set _class = "col"+(_a+1)>>
<<if _column == 0>>
<<set _table += "<tr>">>
<</if>>
<<set _table += "<td><div class='"+_class+"'>You are player "+_a+"</div></td>">>
<<if _column == 1>>
<<set _table += "</tr>">>
<</if>>
<<set _column = (_column+1)%2>>
<</for>>
<<set _table += "</table>">>
_table