0 votes
by (260 points)
Is it possible to put a macro within an html tag?  I'd like to have the source of an image be based on a $var, and I can't use SugarCube's image markup as I want to specify the image size.

So far I've managed this by setting the image source after the fact, in an 'onLoaded' event in a script macro, but this seems clunky.

1 Answer

0 votes
by (37.1k points)

You can set the source of an image with a story variable using an "attribute directive" like this:

<img @src="'images/'+$var">

The "@" before the attribute name tells SugarCube to evaluate the contents of that attribute.

NOTE: Using attribute directives may require updating to SugarCube v2.23.5 or later due to a bug in earlier versions of SugarCube.  Download the latest version of SugarCube v2 (currently v2.27.0) and install the updated format into Twine.  Then do "Change Story Format" in the Twine editor in your story, and set it to the updated version of SugarCube.

If you wanted to trigger a macro in the "onload" event for that image as well, you could do this:

<img @src="'images/'+$var" onload="$.wiki('<<macroName>>')">

That uses jQuery in the "onload" event to call the macro named there.  See jQuery.wiki() for details.  (NOTE: Outupt from wiki code in a "$.wiki()" call will not be directly displayed.  To get around that you can use the <<replace>> macro if you need some output displayed somewhere.)

Hope that helps!  :-)

by (260 points)

That's pretty powerful, thanks a lot!  I'll happily grab the latest SugarCube for this.
Welcome to Twine Q&A, where you can ask questions and receive answers from other members of the community.

You can also find hints and information on Twine on the official wiki and the old forums archive.

See a spam question? Flag it instead of downvoting. A question flagged enough times will automatically be hidden while moderators review it.