Using a String Variable to Modify a CSS Class

Twine Version: 2.3.14
Story Format: Sugarcube 2.34.1

Good afternoon!
I’ve been developing a tile-based worldmap using HTML and CSS. The map itself is a table, with each tile being a data point. Using a for loop, each time a data point is generated, the iteration of the for loop (_i) checks a global array variable called $tileContents, which returns a value. This value is then sent through a series of IF statements, which then determine what CSS class that value is referring to.

For instance, say it’s the third run of my for loop; this means I’m working on my third tile on the map. To get the contents/CSS class of this tile, I check in the third index of the $tileContents array. Say it returns a 1; this value then goes through a series of IF statements. A 0 would mean it’s an empty tile, a 1 means it’s a wall, a 2 means it’s a player, etc. In this case, tile 3, with a tile ID of 1, would be a wall, so it generates <td class="wall"></td>.

The same IF statement is ran for every row in the table, meaning if I had a map that was 10 by 10, I’d have 10 sets of the same IF statements checking tile IDs–one set for each row. I was hoping to change this to instead be a function or something like that (intuition from when I took a high school compsci class). I figured the best way to do this was to just <include> a passage with all the code in it, that way each time the for loop runs, it’d inject all the IF statements in right there.
I managed to get this partially working (read: no error messages) by globalizing _i and a few other variables, but then realized that I had to move my <td> out of the ‘function’ passage and back into the passage with the <table> in it if I wanted anything to actually generate. This meant that, instead of running an IF statement that generates a <td> with a preset class, I’d instead have to make the IF statement change a “tileContents” variable, and then set the external <td>'s class using that string variable.
I was hoping that it’d be as simple as <td class=$tileContents></td>, but that doesn’t seem to be the case. I’m hoping there’s an easy solution to this, since I’m really not the best at coding, especially in JavaScript lol

If it makes things easier, you can probably eliminate all of those if statements with a simple trick.

Since all of your ID are associated with the a list of classes, you can put this in your javascript passage:

setup.classes = {
    0: "empty", 
    1: "wall",
    2: "player"

And then in your loop:

<td @class="<<= setup.classes[$tiles[_i].type]>>"></td>

Something like that. I didn’t test it but I think it should work.

It seems like you were going in the right direction but you’re missing a critical piece: you need to slap a @ on html attributes that you want to evaluate twine script inside. (It’s kind of strange, I know.)

Here’s the reference on that.