quarkusquarkus-qute

How to inject a JS script in Qute Template Engine


I am using Quarkus with the qute template engine. I need to inject some dynamic js script to load on the HTML page. But qute convert js like this:

Template file hello.html:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>redirect by script</title>
    </head>
    <body>
        <p>Hi {name}!</p>
    <script>
        {script}
    </script>
    </body>
</html>

Controller

@RequestScoped
public class Resource {
  @Inject
  @Location("hello.html")
  Template hello;

@Route(path = "/s/:name", methods = HttpMethod.GET)
  public Uni<String> rScript(RoutingContext rc) {
    String s = "console.log('Hi from script');";
    return Uni.createFrom().completionStage(() -> hello
            .data("name", rc.request().getParam("name"))
            .data("script", s)
            .renderAsync());
  }
}

The template render file like below and script will not run on browser:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>redirect by script</title>
    </head>
    <body>
        <p>NOT_FOUND!</p>
    <script>
        console.log(&#39;test redirect by script&#39;)
    </script>
    </body>
</html>

How can I pass script data to qute template file?


Solution

  • You will want to turn off Character Escapes:

    Either use raw:

        <script>
            {script.raw}
        </script>
        </body>
    </html>
    

    Or return a RawString:

    @Route(path = "/s/:name", methods = HttpMethod.GET)
      public Uni<RawString> rScript(RoutingContext rc) {
        String s = "console.log('Hi from script');";
        return Uni.createFrom().completionStage(() -> hello
                .data("name", rc.request().getParam("name"))
                .data("script", new RawString(s))
                .renderAsync());
      }
    }