EzDevInfo.com

twirl

The Play Scala Template Compiler

Preprocessing of sbt-twirl templates

I need to preprocess some Twirl templates in my sbt project. Is it possible to define a task in build.sbt that will run before Twirl plugin compiles its templates?


Source: (StackOverflow)

Load twirl template dynamically

In my Scala project I use Twirl template engine. Template files structure is duplicated for russian and english languages so for example I have the following two paths: en.Send.txt.MonoEnsure and ru.Send.txt.MonoEnsure

In my code I want to be able to dynamically load en or ru template, something like this:

def render(lang: String) = lang.Send.txt.MonoEnsure("hi")
render("en") // does not work, just to illustrate my point

How can I achieve this?


Source: (StackOverflow)

Advertisements

Twirl templates cannot be seen in the code (spray application)

I have some configuration problem I can't see. I've followed the instructions provided in the latest twirl README, but the html package is undefined according to the compiler.

  1. I've included the sbt-twirl plugin in the project/plugins.sbt file

    addSbtPlugin("com.typesafe.sbt" % "sbt-twirl" % "1.0.3")
    
  2. In the project/Build.scala I've enabled the plugin

     lazy val root  = Project(id = "proj", base = file("."))
       .enablePlugins(play.twirl.sbt.SbtTwirl)
       .settings(rootSettings: _*)
    
  3. I've placed the page.scala.html in the src/main/twirl subdirectory (either directly or using the com/somethin/cool path)

Now if I'm trying to import the html package (or com.somethin.cool.html) the compiler complains it's undefined. I can compile the templates with 'twirlCompile' command, and they get properly generated in the target subdirectory, but they are invisible to the main project.

Note: This is not a PlayFramework project

  • Scala: 2.10.4
  • sbt: 0.13.6
  • twirl: 1.0.3

Source: (StackOverflow)

illegal start of simple expression

I am trying to execute a simple java program using play. I am getting a compilation error as illegal start of simple expression. I have searched answers for this question, but I didn't get it. My code looks like this:

@(products :List[Product])
@main("Products catalogue")
<h1> All Products </h1>
<table class="table table-striped">
<thead>
<tr>
<th> EAN </th>
<th> NAME </th>
<th> DESCRIPTION </th>
</tr>
</thead>
<tbody>
@for(product <- products)
{
<tr>
<td><a rel='nofollow' href="@routes.Products.details(product.ean)"> @product.ean </a></td>
<td><a rel='nofollow' href="@routes.Products.details(product.ean)"> @product.name </a></td>
<td><a rel='nofollow' href="@routes.Products.details(product.ean)"> @product.description  </a></td>
</tr>
}
</tbody>
</table>

I am getting the error at the for loop. Can u help me to solve this problem?


Source: (StackOverflow)

Code assistance in IntelliJ IDEA for implicit variables in Twirl Template

I am building a web app in Java using the Play! framework and Twirl template engine, using IntelliJ IDEA. In the template there are a number of implicit variables which are available(flash, session, requestHeader). I can successfully reference any of these variables and my app will compile and run as expected. However, as these variables have not been explicitly declared, IDEA shows an error(eg. Cannot resolve symbol flash) and does not provide any code assistance. While it is not a huge problem I would like to fix this if possible.

I have searched quite a bit for a solution, and the JetBrains blog has a post on how to do this for Velocity templates, if someone could help me do the same for Twirl templates I would be very thankful!

Jackson


Source: (StackOverflow)

Use Twirl with Spring MVC

Is it possible to use Twirl with Spring MVC as the view technology? I would like to use something in place of JSP, and Apache Tiles feels cumbersome to me. Twirl the view technology for the Play Framework looks very cool, and similar to ASP.NET Razor.

https://www.playframework.com/documentation/2.3.x/JavaTemplates

I did a quick Google search but did not uncover much.


Source: (StackOverflow)

How to inspect values of settings in Seq[Setting[_]]?

I'm trying to read the values of twirlSettings defined in SbtTwirl.

Is there a way to do it? Perhaps using sbt inspect? Or is there any other way? I need to read the values as I'm trying to find out why my Twirl templates don't get compiled.


Source: (StackOverflow)

Play Framework - how to walk tree of JsonNode in view?

Hi I am trying to display nested JSON data in my view, similar to how it appears in the Advanced REST Client when you get a response from an API.

I found this question which basically asks the same thing I am asking; however, I want to display the result in a view using the Play Framework 2.3.x. I know that I need a recursive function to display all the json objects, so I've tried using a reusable block in my view. Here's what I have right now:

@(fromAPI: com.fasterxml.jackson.databind.JsonNode)

@import com.fasterxml.jackson.databind.JsonNode

@walkJsonTree(name: String, node: JsonNode) = {

    @if(node.isObject()) {

        @for(nodeEntry <- node.fields()) {
            <li>@nodeEntry.getKey(): </li>
            <ul>@walkJsonTree(nodeEntry.getKey(), nodeEntry.getValue())</ul>
        }
    }
    @if(node.isArray()) {
        @for(arrayNode <- node.fields()) {
            <li>[List]: </li>
            <ul>@walkJsonTree(arrayNode.getKey(), arrayNode.getValue())</ul>
        }
    }
    @if(node.isValueNode()) {
        <li>@node.asText()</li>
    } else {
        @* other *@
        <li>@node.asText()</li>
    }

}

@main("API Response") {

    <div class="container">
        <h3>API Response</h3>

        <ul>
            @walkJsonTree(null, fromAPI)
        </ul>
    </div>
}

Unfortunately, this is not displaying the JSON properly. It only displays the first object's name based on this line <li>@nodeEntry.getKey(): </li>. What am I doing wrong? Does anyone have any other suggestions for displaying JSON in a nested manner?

Thanks!


Source: (StackOverflow)

Play Framework trouble importing scala template from different package

Using Play 2.3.7, I have a set of bootstrap3 templates similar to this example project, and they are in a package app/views/bootstrap3/. One of these bootstrap3 templates is a text field object in a file named text.scala.html. In a separate package, I have some other templates in which I want to use my custom text field. So, in package app/views/other/ let's say I have I have a file index.scala.html, how do I correctly import my Bootstrap3 templates? This is what I have in my code

@import views.bootstrap3._

@* my bootstrap3 text field template *@
@text("some", "params", "here")

However, when I try to compile I get an error in index.scala.html (line 3) saying that

package scala.text is not a value

How do I fix my code so that I can import my templates from a separate package?


Source: (StackOverflow)

Check Html fragment nullity with Play Framework 2.3.0

I have a tag in my application with the following structure :

@(
    columns: Integer
)(header: Html)(body: Html)

<table>
    @if(header != null) {
        <thead>
            <tr>
                @header
            </tr>
        </thead>
    }
    // Body and foot here
</table>

And I use it in my template like this :

@tags.Table(5) { } {
    // My content here
}

The previous code does not work : even if I let the brackets empty, the <thead></thead> is displayed. So how to check that the header is not empty, null... and how to declare my tag in my template ? Maybe I'm wrong declaring it with { } ?

If I declare it with {}, I have the following error :

type mismatch;
 found   : Unit
 required: play.twirl.api.Html

Source: (StackOverflow)

Order of elements shown in generated HTML doesn't match the order of the elements in the collection

I'm getting crazy in struggling to understand why is this happening: I have a collection (a immutable SortedSet) containing 6 integers, and I iterate on them via .map method to create my generated HTML. The elements in the HTML page always show in different order every time I reload the page.

Here's some excerpts from my template

@deltas = @{ scala.collection.SortedSet[Int]( -15, -10, -5, 5, 10, 15) }

     @*** More code here ***@

@Logger.debug("DELTAS="+deltas.toString())
@deltas.map { delta =>
<li>
  @Logger.debug("DELTA="+delta.toString())
  <a rel='nofollow' href="#">@{dist.toDouble.intValue + delta}&nbsp;km (@delta)</a>
</li>
}

I also tried to Log the output to the screen - see Logger - and as expected the elements are always shown in the correct order.

[debug] application - DELTAS=TreeSet(-15, -10, -5, 5, 10, 15)
[debug] application - DELTA=-15
[debug] application - DELTA=-10
[debug] application - DELTA=-5
[debug] application - DELTA=5
[debug] application - DELTA=10
[debug] application - DELTA=15

Now I can only say the issue must be in the template engine, but I'd like to know whether it is a bug (unlikely) or I just need to know something more about some tricky aspect of it (very likely).


Source: (StackOverflow)

Big Double in Scala templates and Play Framework

I'm using Play Framework 2.3.6 and Scala

When I'm trying to display input with big Double i.e. 55 000 000 it displays in input 5.5E7

@inputText(field("price"), '_label -> "Price")

<input type="text" id="price" name="price" value="5.5E7">

How can I change default formatting or somehow display it properly?


Source: (StackOverflow)

Twirl repeated form field only first button updates

I've attached the picture of my interface, which is created with the following twirl template code:

@(interests:List[String],levelsForm: Form[ManyInterests],user:models.User)(implicit request: RequestHeader,messages: Messages)

@import helper._
@import play.api.Play.current


@import b3.vertical.fieldConstructor
@opts = @{ Seq("1"->"Not very passionate","2"->"A little passionate",
    "3"->"Moderately passionate","4"->"Very passionate","5"->"Extremely passionate") }

@main("Passion Levels",Some(user)) {
    <h3>For each of the previous entered interest and activities, please rate how passionate you are:
    </h3>
    @helper.form(action = routes.ResponseController.newPassion) {
    @interests.map { interest =>
            <span><b>@interest</b></span><br />
        @b3.radio(levelsForm("interestpassions"), options = opts,'_inline ->true)
    }
        @b3.buttonType("submit", 'class -> "btn btn-default"){Next}
    }
}

radio buttons

It generates the correct mapping of radio buttons for value pulled from a pgsql query, but the problem i am facing is that when I click on ANY radio button, the only row that displays changes is the very first row. So to explain using the image, if I select 'Very Passionate' for playing soccer, the radio button does not render an entry here, but the selection for the first passion of 's' changes to 'Very Passionate.'

I'm not sure how to remedy this. I'm using play-bootstrap3 which has worked great for all my other form components.


Source: (StackOverflow)

template scala Playframwork

It is my first playframework project using scala template and i m looking forward some help. When i compile my code , it generetes an error : '(' expected but ')' found

 @(produits : List[models.Produit], messages : List[String])
        <div class="container padding-top-10">
            <div class="jumbotron">
                <form class="register form-horizontal" action="@routes.Application.objectif_dc()" method="POST">

                    <label for="produit">
                        produit :
                        <br/>
                        <select name="produit" class="form-control">
                            @for ( produit <- produits){
                            <option value="@(produit.id)"> @(produit.type) </option>
                            }
                        </select>
                    </label>

                    <br/>
                    <br/>
                    <label for="cible">
                        cible :
                        <br/>
                        <select name="cible" class="form-control">
                            <option value="cdd" selected>chef de departement direct</option>
                            <option value="cdi">chef de departement indirect</option>
                        </select>
                    </label>

                    <br/>
                    <br/>
                    <label for="objectif">
                        Objectif :
                        <br/>
                        <input type="text" class="form-control" name="objectif" placeholder="objectif" value="" />
                    </label>
                    <br/>
                    <br/>
                    <button class="btn btn-default" type="submit">envoyer</button>
                </form>
            </div>
        </div>

Source: (StackOverflow)

Simplify/DRY up a case statement in Scala for Twirl Templates

So I'm using play Twirl templates (not within play; independent project) and I have some templates that generate some database DDLs. The following works:

if(config.params.showDDL.isSupplied) {
    print( BigSenseServer.config.options("dbms") match {
      case "mysql" => txt.mysql(
        BigSenseServer.config.options("dbDatabase"),
        InetAddress.getLocalHost().getCanonicalHostName,
        BigSenseServer.config.options("dboUser"),
        BigSenseServer.config.options("dboPass"),
        BigSenseServer.config.options("dbUser"),
        BigSenseServer.config.options("dbPass")
      )
      case "pgsql" => txt.pgsql(
        BigSenseServer.config.options("dbDatabase"),
        InetAddress.getLocalHost().getCanonicalHostName,
        BigSenseServer.config.options("dboUser"),
        BigSenseServer.config.options("dboPass"),
        BigSenseServer.config.options("dbUser"),
        BigSenseServer.config.options("dbPass")
      )
      case "mssql" => txt.mssql$.MODULE$(
        BigSenseServer.config.options("dbDatabase"),
        InetAddress.getLocalHost().getCanonicalHostName,
        BigSenseServer.config.options("dboUser"),
        BigSenseServer.config.options("dboPass"),
        BigSenseServer.config.options("dbUser"),
        BigSenseServer.config.options("dbPass")
      )
    })

    System.exit(0)
}

But I have a lot of repeated statements. If I try to assign the case to a variable and use the $.MODULE$ trick, I get an error saying my variable doesn't take parameters:

val b = BigSenseServer.config.options("dbms") match {
      case "mysql" => txt.mysql$.MODULE$
      case "pgsql" => txt.pgsql$.MODULE$
      case "mssql" => txt.mssql$.MODULE$
}
b("string1","string2","string3","string4","string5","string6")

and the error:

BigSense/src/main/scala/io/bigsense/server/BigSenseServer.scala:32: play.twirl.api.BaseScalaTemplate[T,F] with play.twirl.api.Template6[A,B,C,D,E,F,Result] does not take parameters

What's the best way to simplify this Scala code?

EDIT: Final Solution using a combination of the answers below

The answers below suggest creating factory classes, but I really want to avoid that since I already have the Twirl generated template object. The partially applied functions gave me a better understanding of how to achieve this. Turns out all I needed to do was to pick the apply methods and to eta-expand these; if necessary in combination with partial function application. The following works great:

  if(config.params.showDDL.isSupplied) {

    print((config.options("dbms") match {
      case "pgsql" => 
        txt.pgsql.apply _
      case "mssql" => 
        txt.mssql.apply _
      case "mysql" => 
        txt.mysql.apply(InetAddress.getLocalHost().getCanonicalHostName,
                        _:String, _:String, _:String,_:String, _:String)
    })(
        config.options("dbDatabase"),
        config.options("dboUser"),
        config.options("dboPass"),
        config.options("dbUser"),
        config.options("dbPass")
    ))

    System.exit(0)
  }

Source: (StackOverflow)