Can I programatically use Tags to load, position, and size arbitrary images without having code in every passage?

Twine Version: 2
Story Format: Harlowe

I’ve been stumbling through old forum and blog posts, and have some ideas of how to do this but haven’t been able to get anything properly working yet.

For an example, I have this in my css stylesheet;

tw-story[tags="John"] {
   background-color: yellow;

if I put this into my passage at the top

(if: (passage:)'s tags contains "John")[ <img src="images/garfield.jpg"> ]  ]

it loads a picture of garfield.

But I would like to keep all of my code in one central location. I’ve heard that a StoryInit passage can run code at the start of the story so I’ve been trying to get that working in there but that hasn’t worked out yet. I was thinking I might need to put it in a loop so it keeps looking, and tried that with this

(for: (passage:)'s (if: (passage:)'s tags contains "John")[ <img src="images/garfield.jpg"> ])

but that wasn’t working either.

Could someone point me in the right direction?

I’ve also seen a few people doing sort of similar stuff from the Story Javascript sheet. I would be open to using that as well, or whatever I need really I’m pretty familiar with programming I’m just not entirely sure how twine structures this sort of stuff yet.

Thanks in advance for any help :slight_smile:

I solved my own problem.

Here is what I did;
What I ended up going with in harlowe (for anyone that stumbles across this in a search) is;

In my CSS Stylesheet

tw-story[tags="John"] { background-color: yellow;}

Then I figured out I needed a StoryInit passage which I then put

(if: (passage:)'s tags contains "John")[ <img src="images/garfield.jpg"> ]

and then tagged the passage with ‘startup’

Now I don’t have to have code in every passage I can keep it all in one central location (as is best OOP practice) and keep my dialogue passages clean. Now I just need to work out the sizing and positioning code but that should be easier than figuring out the tagging pictures into a passage code.

A couple of clarifications regarding Harlowe and your solution:

1:The Passage name StoryInit only has special meaning in a SugarCube based project.
2: Adding a startup Passage Tag to a Passage causes the contents of it to be executed before (and only then) the project’s initial Passage is shown.

If you want your (if:) related code to be executed before each and every Passage that is shown then you need to assign a header Tag to it instead.

Ok I see, I’ll have to be more careful about that.

That makes sense, if it only runs the first time all my successive passages wouldn’t have their content run. I guess I would use startup for more first time variable setup and stuff.

Thanks for the help, this should get me moving on my project.