[Sugarcube] Print variable inside of quotes

I would like to use a variable for the path of an image. Here is the code I have:

<<widget "chat">>\
  <div class="chat"><img src="img/$args[0]/p.png" width="50px"> $args[0] <hr> $args[1]</div>
<</widget>>

The $args[0] inside of the quotes is printing as text and not the variable. How can I change this code to actually print the variable? The second $args[0] and $args[1] is working as expected.

1 Like

If you want SugarCube to modify the contents of an attribute in an HTML element, then you have to use attribute directives. To do that, you basically stick an @ in front of the attribute name, and then you treat the contents of the quoted attribute value as code to be evaluated.

For your code, that would look like this:

<<widget "chat">>\
  <div class="chat"><img @src="'img/' + $args[0] + '/p.png'" width="50px"> $args[0] <hr> $args[1]</div>
<</widget>>

And that sets the src attribute to whatever this code evaluates to: 'img/' + $args[0] + '/p.png' . For example, if $args[0] was set to “Anne”, then it will act like it’s this: src="img/Anne/p.png"

Hope that helps! :slight_smile:

1 Like

That’s exactly what I wanted. I was trying to javascript without the @ and it obviously wasn’t working. Thank you!

Edit: Oops, too late. Well, I can’t delete the post, so I’ll just leave my answer here.

If you want to use the value of a variable inside of an HTML attribute, you’ll need to use the @ operator. When this is put before the name of an attribute, it tells SugarCube to treat whatever is inside the quotes like an expression, which it evaluates to get the actual value of the attribute. So, your src attribute should look like this:

@src="'img/' + $args[0] + '/p.png'" 

So, you’ll treat it as if you are building a string using variables, except that all of it will need to be enclosed in double-quotes, so it’s best to use single-quotes (’) around the bits that are plain text. Do this for any attribute which you want determined by the value of a variable.

1 Like