Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Variable in HTML tag

I'm trying to use a variable in an HTML tag under Harlowe.
<img src = $image />
But $image is printed verbatim in the page code and not translated to his value. Any idea of how to code this properly ?
Thanks a lot.

Comments

  • You use a (print: ) macro to dynamically create the the img element.
    (set: $image to "smile.png")
    
    (print: '<img src="' + $image + '">')
    
  • It works. Thanks
  • edited May 2016
    Hello - I am trying to apply something similar to the html 5 progress element - can you tell me where I'm going wrong?
    (set: $progress to 50)
    
    (print: '<progress max="100" value="' + $progress + '"></progress>')
    

    When previewing the code, I get an error stating 'the number 50 isn't the same type of data as the string "\"></progress>"

    Sorry, should point out I'm using Harlowe/online version of Twine 2.0.11.
  • bawpie wrote: »
    ... the number 50 isn't the same type of data as the string ...
    Javascript (and the Twine Story Formats) supports different data types, two of them being Number and String.

    By default you can't "add" two values of different types together without first converting one (or both) of the values into the same data type (**). This is what the error message is trying to explain.

    You can use the (text: ) macro to temporary convert the Number stored in the $progress variable into a String like so:
    (set: $progress to 50)
    
    (print: '<progress max="100" value="' + (text: $progress) + '"></progress>')
    

    ** There are times when Javascript will do the data conversion automatically for you (this is not one of them) but it is generally not a good idea to rely of that feature because it can get it wrong. It is better to do manual conversions instead because you get to control exactly what is being converted and to what data type it is being converted to.
  • Thanks greyelf - that makes sense, I'm guess I didn't think that that the progress element would expect a string rather than a number though - but I guess this is because it's all a string?
  • bawpie wrote: »
    ... but I guess this is because it's all a string?
    In this case it is the parameter that you are passing to the (print:) macro that is the String, and this is why you need to convert the Number value so that you can "add" it to that String.

    String values are always wrapped in quotes (single or double)

    The values assigned to the attributes of a HTML tag are a strange case because they are always wrapped in quotes even when the values are not Strings, this is because in the past HTML considered everything to be a String.
  • Brilliant, thank you.
Sign In or Register to comment.