Using Sugarcube 2
I have a div in my passage,
<div id="myButtons></div>
and a template for a button,
<span class="btn"><<button "%value%>><<set $selected to "%value%">></span>
I have an array of values,
var values = ["high", "medium", "low"];
I'dd like to generate a button for each of those and add to to the div "myButtons".
So far I tried doing it in Javascript with a postdisplay, but the Twine code isn't interpreted. Any other Task Objects don't do anything.
I'm not too familiar with Twine, but I know Javascript. How do I properly "inject" my generated buttons?
Comments
The next easiest thing would probably be to print the markup using a function: (Twine 1: goes in a script-tagged passage; Twine 2: goes in Story JavaScript) Usage:
Untested, but either of those should work.
PS: You have a few missing quotes in your examples. You might want to keep an eye on that.
My main issue is that since I need to access these variables from Javascript, I need to declare them as state variables ($). But after I print the code, my <<forget>> statement does not remove them from the state. So I am stuck carrying those around.
From what I see, I think I should switch to full-Javascript for this with
Is Wikifier the equivalent of "<<=...>>"? The name throws me off, I am wondering if there is any kind of catch with that.
Issues:
May I suggest: You don't actually need the <<=>> macro here because of the naked variable markup, but I left it in since that's what you were using.
You don't need to use JavaScript. TwineScript constructs, which have native access to both types of variables, work just as well in most cases—as I've shown above.
Assuming for the moment that dropping down to pure JavaScript was necessary in this instance, you may access temporary variables via the TempVariables object and story variables via the State.variables object or the variables() story function, which returns a reference to the object—you, obviously, know about the latter.
I've already explained what you did wrong with <<forget>>.
Full stop. I recognize that macro "template" and you can toss it into the garbage where it belongs.
Read SugarCube's macro API.
As I've shown above, what you want to accomplish is easily handled without dropping to pure JavaScript. If you want to, that's perfectly fine. You do not, however, need to.
That said, I can provide an example of such a macro: (based on your example code)
If the "values" object you're passing in is actually an array, as in your first examples, then a better way to do this would be the following: Because using Object.keys() on an array is just plain silly.
Not quite. The <<=>> macro is an alias of the <<print>> macro. The reason it works is because the printed value is passed through the Wikifier.