How to use a variable to define a path to an image?

Hello guys,

I need to introduce an image as an object property so i can use it later, calling that property. I don’t seem to find a solution to that problem. One possible solution was to define the path to the image as a variable. I tried to use the [img]markup to no success. For example, the following code doesn’t work:

<<set $image = “C:\Documents\Twine\Stories\images\burguer.png”>>


The image doesn’t display, although the image path is correct. If i state


the image displays correctly as expected.

Some help with this issue would be much appreciated,

thanks in advance

PS - I’m using TWINE with SUGARCUBE 2.21.0


Well, two problems with your <<set>> line. First, make sure you’re using standard double quotes like "text" and not fancy double quotes like “text” (I’m not sure if the forum software changed that for you above, but if so, you should use the “Preformatted text” button to avoid that). Second is that, instead of using backslashes (\) for your file paths, you should use slashes (/), because backslashes have a special meaning within quotes on web pages (see the “Special Characters” section here for details).

Assuming the path and filename are correct, this should work:

<<set $image = "C:/Documents/Twine/Stories/images/burguer.png">>

This brings up a different problem. That code will only work on your computer. So, instead of using an absolute path like that, you might want to write your code to use a relative path when not running inside of Twine. To do that, you can put this in your JavaScript section:

if (window.hasOwnProperty("storyFormat") || (document.location.href.indexOf("AppData") !== -1)) {
	/* Change this to the path where the HTML file is
		 located if you want to run this from inside Twine. */
	// Running inside Twine application
	setup.Path = "C:/Games/MyGame/";
} else {
	// Running in a browser
	setup.Path = "";
setup.SoundPath = setup.Path + "sounds/";
setup.ImagePath = setup.Path + "images/";

Just change "C:/Games/MyGame/" to the path where your game’s HTML file is, and change "images/" or "sounds/" if you have different subdirectories for them.

Now you can write your code any of these ways:

<<set $image = setup.ImagePath + "burguer.png">>
- or -
[img[setup.ImagePath + "burguer.png"]]
- or -
<img @src="setup.ImagePath + 'burguer.png'">

and now your code works both within Twine and in the published version.

Enjoy! :slight_smile:

P.S. SugarCube v2.29.0 is the current version, so you might want to grab it and install it.


Hello HiEv,

It works perfectly. Thank you very much.

And thank you for your advice concerning the relative path. I was aware that it was an issue but i decided to address that problem later. But looks like you already did that for me. :ok_hand: Thank you very much! You were very helpful.

Cheers mate,

1 Like