Search code examples
javascriptjquerythymeleaf

Using javascript in thymeleaf th:src


I'm trying to do something like this:

 <iframe th:src="'myFunction($videoUrl);'"></iframe>

where myFunction is a jQuery function. I want the src value to be the output of the function.

So far, I've tried

<iframe th:src="'javascript:myFunction(\''+ ${videoUrl} +'\');'" ></iframe>

However the output is not the result of the function, but the function with the url as attributeL. I'm guessing this works well with onClick, but it's not what I'm looking for.

Is it possible?


Solution

  • Uhh... thymeleaf/javascript just don't work this way. Instead of trying to set the source directly with a javascript function, you should be doing this in a document ready block. Something like this for example:

    <script type="text/javascript" th:inline="javascript">
      $(function() {
        var url = [[${videoUrl}]];
        $('#video').attr('src', myFunction(url));
      });
    <script>
    
    <iframe id="video"></iframe>