Using @{} in image onerror attribute

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Using @{} in image onerror attribute

benr

I have an onerror attribute on an <img> tag that should look as follows when rendered:

<img ... onerror="this.src='/CONTEXT/images/image.png';"/>

however, I'm having trouble writing a th:onerror attribute to cause this to be generated. I've tried:

th:onerror="${'this.src=\'' + @{/images/image.png} + '\';'}"

which generates an exception: java.lang.IllegalStateException: Cannot handle (92) '\'.

Other variants won't compile either. How do I write the th:onerror attribute to generate the correct value? I want to avoid specifying CONTEXT manually.

Cheers,
Ben

Reply | Threaded
Open this post in threaded view
|

Re: Using @{} in image onerror attribute

danielfernandez
Administrator
Everything inside a ${...} is considered to be a SpringEL expression (or OGNL, if you don't use Spring). And you have no need to use an expression language to append string literals:

  th:onerror="'this.src=\'' + @{/images/image.png} + '\';'"

Note that, once processed, thymeleaf will write your ' symbols as &#39;, their escape code. This is because the rules of well-formed markup require attribute values to escape all XML entities inside them (&quot;, &lt;, &gt;, &amp; and &apos;), but Internet Explorer does not recognize &apos; so its numeric code is used instead for better compatibility.

Regards,
Daniel.


Reply | Threaded
Open this post in threaded view
|

Re: Using @{} in image onerror attribute

benr
Thanks Daniel, much appreciated.