Jake
Jake

Reputation: 4660

thymeleaf javascript onload=location.href

Hopefully this is a simple syntax question:

I want to create an onload statement that, when compiled, will look as follows:

<body onload="location.href='#tutanchor'">

My expression language attempt is as follows:

<body th:attr="onload='location.href='+${anchorname}">

This doesn't work because it is missing the single quotes round the anchor. But if I add additional single quotes, thymeleaf cannot parse.

Any suggestions?

Upvotes: 0

Views: 10422

Answers (1)

gilly3
gilly3

Reputation: 91497

How about using &apos;?

<body th:attr="onload='location.href=&apos;'+${anchorname}+'&apos;'">

I'm not familiar with thymeleaf, so this may not work as I expect. The documentation suggests that \ is the escape character for quotes. If &apos; doesn't work, try escaping the quotes:

<body th:attr="onload='location.href=\''+${anchorname}+'\''">

It begs the question, why not just use a <script> tag?

<script th:inline="javascript">
/*<![CDATA[*/
    location.href = /*[[${anchorname}]]*/ '#';
/*]]>*/
</script>

Upvotes: 2

Related Questions