Scala: How to include a JS script to Mustache template in Finatra?

451 Views Asked by At

I'm trying to include a JS script within my mustache template file.

<html>
<head>
    <script id="{{app.js}}" type="text/mustache"></script>
</head>
<body>
<div>
    Users:
    <ul>
        {{#users}}
            <li>{{name}}</li>
        {{/users}}
    </ul>
</div>
</body>
</html>

It is located in src/main/resources/templates/users.mustache. Also I have a JS script in src/main/resources/public/app.js.

A few words about backend. I'm using Finatra framework with support of Mustache out of the box:

  get("/users") {
    req: Request => {
      response.ok.view("/users.mustache", Users)
    }
  }

So here is my question. How can I add a JS script to my Mustache template?

UPD

I also tried to use

<script src='{{path}}/public/app.js' type='text/javascript'></script>

But my app still doesn't see the script.

UPD2 (thx to @nuc)

I didn't find any good solution but only this one:

get("/public/:*") {
  req: Request => {
    req.params.get("*") match {
      case Some(fn) =>
        val file = new File("/Users/fink/projects/finatra-demo/src/main/resources/public/" + fn)
        response.ok.file(file)
      case None => {
        response.notFound("Oh no!")
      }
    }
  }
}

I placed all assets to

src/main/resources/public/*

And in my view it should be <script src='/public/js/app.js' type='text/javascript'></script>

1

There are 1 best solutions below

4
On

You need to have an additional route to serve your js file, named to the prefix/convention you're using.

get("/assets/js/:file") { request: Request =>
    response.ok.file(request.getParam(file))
}

See http://twitter.github.io/finatra/user-guide/files/