r/twinegames • u/nolanfa • 21d ago
SugarCube 2 use a variable as span id used in replace
Hi!
I'd like to use a variable as a span id, that will be targeted by a replace. It doesn't work so far. Is it possible?
This works (without variable):
<span id="oi">Oi!!</span>
<<link "clicky!">><<replace "#oi">>ow<</replace>><</link>>This doesn't (exact same but with a variable) ("private names aren't valid in this context"):
<<set $ouch to "ouch">>
<span id=$ouch>ouch</span>
<<link "clicky!">><<replace `#$ouch`>>ow<</replace>><</link>>This doesn't either (same too but a different way to set the variable) ("no element matched selector"):
<<set $heyWord to "hey">>
<<set $hey to "#" + $heyWord>>
<span id=$heyWord>hey!!</span>
<<link "clicky!">><<replace $hey>>ow<</replace>><</link>>This works, so I assume the issue is with the span and not with the replace:
<<set $wowWord to "wow">>
<<set $wow to "#" + $wowWord>>
<span id="wow">Wowwww...</span>
<<link "clicky!">><<replace $wow>>ow<</replace>><</link>>Is there a solution?
(I'm trying to generate this block with a widget, and pass the widget the value of the var that will be used as span id; I could just type it all out every time I need it - and will if there's no other solution - but I was looking for a more convenient way to do it)
4
u/HiEv 21d ago
You can't just stick a variable into an HTML element, you need to mark it so that SugarCube will know it needs to be converted. You can do that by putting an "
@" in front of the attribute name within the HTML element, which tells SugarCube to evaluate the value of that attribute before removing the "@". For example:The "
@" causes the span to be rendered as<span id="owie">in the above code.The backticks within the
<<replace>>cause it to evaluate the contents within the backticks, so it's effectively doing<<replace "#owie">>in the above code.Enjoy! 🙂
1
u/GreyelfD 20d ago
The
@symbol usage mentioned by HiEv is known as Attribute Directive markup in the SugarCube documentation, and information about using back-quotes (aka backticks or grave-accent) to force the evaluation of an expression can be found in the Argument type macros: passing an expression as an argument section of the Macro Arguments documentation.