Table of contents
1.
Introduction💁
2.
Twirl Template Engine 🌀
3.
Syntax
3.1.
The @ Character
3.2.
Parameters
3.3.
Iteration In Scala
3.4.
Conditional Statements
3.5.
Reusable Blocks
3.6.
Comments
3.7.
String Interpolation
3.8.
Scala Types
4.
Dependency Injection With Templates
5.
Common Use Cases
5.1.
Layout
5.2.
Tags
5.3.
Includes
6.
Custom Format
6.1.
Implement A Format
6.2.
Associating a File Extension to the Format
6.3.
How to tell Play to Make an HTTP Result from a Template Result Type?
7.
Frequently Asked Questions
7.1.
What is JDBC?
7.2.
Who is a Scala Developer?
7.3.
Why are Scala Developers so well paid?
7.4.
Is Scala better than Java?
7.5.
What is the role of a Scala Developer?
8.
Conclusion
Last Updated: Mar 27, 2024
Medium

Scala Developers - The Twirl Template Engine

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction💁

Scala is a computer language for creating robust static systems and functional programs. It is JVM-based and object-oriented. It is capable of interacting with libraries and existing Java programs. The idea of primitive data is absent. Thus it is widely believed to be a static type of language.

Scala

Twirl Template Engine 🌀

Now you might be wondering what actually are template engines. So template engines are basically used when there is a need to build a web application having multiple components. They are used to enable fast server-side rendering. For instance, your web application may have various components such as navigation, body, footer, header, etc. So a template engine might help you write codes faster. 

Twirl Template Engine is a very powerful template engine that is inspired by the designs of ASP.NET. Some of the advantages of using the twirl template engine are,

  • Twirl Template Engine is a compact, fluid, and expressive template engine.
     
  • Twirl Template Engine is very easy to learn and quite similar to your traditional coding.
     
  • Twirl Template Engine is compatible with all the text editors.
     
  • It is not a new language, and Scala developers will find it quite relatable.

Syntax

Before we dive into the syntax of the twirl template engine, let us look at the basic code structure for the twirl template engine.

@(student: Student, subjects: List[Subject])

@* Displaying the name dynamically fetched using Scala *@
<h1>Welcome @student.name!</h1>

@* Displaying all the values present in the Subject list *@
<ul>
  @for(subs <- subjects) {
    <li>@subs.title</li>
  }
</ul>

The above code will be saved with the scala.html extension.

Now, let us discuss some of the commonly used and needed syntax present in the twirl template engine.

The @ Character

The @ character is probably the most important character in Scala Development. It is used to dynamically fetch the values and incorporate them into the HTML page. For instance, in the above code, we used the @ character to fetch the name of the student and the subjects present in the list. Let us look at yet another example for better understanding.

Welcome @(Student.FirstName + Student.LastName)

Parameters

We can also pass some parameters in the HTML code using Scala. For instance, we could declare a variable named “company_name” and assign it the value “CodingNinjas”.

@(title: String = "CodingNinjas")

Iteration In Scala

For

Similar to other programming languages, we can use the for keyword to iterate over the elements present in the list. For instance,

@* Displaying all the values present in the Subject list *@
<ul>
  @for(subs <- subjects) {
    <li>@subs.title</li>
}
</ul>

Conditional Statements

If-Else

Similar to other programming languages, we can use the if-else keyword for conditional statements. For instance,

@if(subjects.isEmpty) {
  <h1>Student has not registered for any courses</h1>
} else {
  <h1>Student has registered for @items.size courses!</h1>
}

Reusable Blocks

Reusable blocks are used to store content that might be used multiple times in the code later on. We can declare a reusable block in Scala using the following code snippet,

@* A reusable block to capitalise all the starting letters in a word. *@
@capitalEveryWord(text: String) = @{
  text.split(' ').map(_.capitalize).mkString(" ")
}


@* Passing the text hello world to capitalise all the first letters. *@
<h1>@title("hello world")</h1>

Comments

Adding comments can be very necessary for your code to make sense. We can add comments in Scala using the following code snippet,

@*
  Anything in this section will be treated as a comment.
*@

String Interpolation

String interpolators are basically used when we need to incorporate a variable in a string message. We can use the String interpolators in Scala by importing the following package,

import play.twirl.api.StringInterpolation

 

An example of String Interpolation would look something like this,

val name = "Your Name"
println(s"Hello, $name")  // Hello, Your Name

Scala Types

We can use the concept of wrapping in the twirl template engine. For example,

<ul>
  <li>@Option("value inside option")</li>
  <li>@List("first", "last")</li>
  <li>@User("Foo", "Bar")</li>
  <li>@List("hello", User("Foo", "Bar"), Option("value inside option"), List("first", "last"))</li>
</ul>
Output

Dependency Injection With Templates

In Scala, we can also directly implement or inject a twirl template inside the controller code. By injecting the twirl template inside the controller code, we can have the template handle its own dependencies rather than having the controller handle all the dependencies. For instance, let us assume we have a template that is dependent on a component named firstComponent. Let us now define the structure of firstComponent,

trait firstComponent {
  /** Provide short form of string if over a certain length */
  def firstComponent(item: String)
}
You can also try this code with Online Java Compiler
Run Code

 Now let us create a template for the project/views/Index.html using this syntax for the constructor,

@this(obForComponent: firstComponent)
@(item: String)

@{obForComponent.obForComponent(item)}
You can also try this code with Online Java Compiler
Run Code

 

And finally, we will define the controller file in the project/controller/firstController.java,

public firstController @Inject()(template: views.html.Index, cc: ControllerComponents) extends AbstractController(cc) {
  def var = Action { implicit request =>
    val item = "Insert a long text in this variable"
    Ok(template(item))
  }
}
You can also try this code with Online Java Compiler
Run Code

Common Use Cases

In this section, let us discuss a few ways to compose twirl templates.

Layout

Let us create the main.scala.html file to act like the main layout file,

@(title: String)(content: Html)
<!DOCTYPE html>
<html>
  <head>
    <title>@title</title>
  </head>
  <body>
    <section class="content">@content</section>
  </body>
</html>

The above code takes two parameters as input: title and content. Now let us utilize it in another template named index.scala.html,

@main(title = "Index") {
  <h1>This is the index page</h1>
}

Tags

Let us create a tag to display a notice in HTML using Scala,

@(level: String = "error")(body: (String) => Html)

@level match {

  case "win" => {
    <p class="win">
      @body("green")
    </p>
  }


  case "lose" => {
    <p class="lose">
      @body("red")
    </p>
  }

}

 

Now let us create the template to incorporate the above-created tag,

@import tags._

@notice("lose") { color =>
  <span style="color:@color">So sorry, you lost the match</span>
}

Includes

There is actually nothing special here. You can just import other templates in your code,

<h1>Home</h1>

<div id="side">
  @common.sideBar()
</div>

Custom Format

The twirl template engine supports various built-in formats such as XML, HTML, etc. Twirl Template engine also provides support for other custom formats.

Implement A Format

In this section, we will discuss how to implement a format in the twirl template engine. Let us start small and discuss how to implement the HTML format in your twirl template engine. The HTML format is defined using the following code,

//defining the class HTML with buffer type.
class Html(buffer: StringBuilder) extends BufferedContent[Html](buffer) {
  // creating an object of val type and assigning it the identifier value using MimeTypes.HTML
  val contentType = MimeTypes.HTML
}


object HtmlFormat extends Format[Html] {
  def raw(text: String): Html = …
  def escape(text: String): Html = …
}
You can also try this code with Online Java Compiler
Run Code

Associating a File Extension to the Format

Before compiling the whole application sources, the templates get compiled into a .scala file by the build process. The TwirlKeys.templateFormats key if an sbt setting of the type Map[String, String], which defines the mapping between file extensions and template formats. For example, if Play doesn't support HTML, you would have to write the following in your build file for associating the .scala.HTML files to the Play.twirl.API.HTMLFormat format.

TwirlKeys.templateFormats += ("html" -> "my.HtmlFormat.instance")
You can also try this code with Online Java Compiler
Run Code

How to tell Play to Make an HTTP Result from a Template Result Type?

For any value of type A for which there exists an implicit value of play.api.HTTP.Writeable[A], Play can write an HTTP response body. So, you must define such a value for your template result type. The following example shows how you can define such a value for HTTP-

implicit def writableHttp(implicit codec: Codec): Writeable[Http] = Writeable[Http](result => codec.encode(result.body), Some(ContentTypes.HTTP))
You can also try this code with Online Java Compiler
Run Code

 

Now let's discuss some frequently asked questions associated with Scala Developers- Accessing a SQL Database.

FAQs

Frequently Asked Questions

What is JDBC?

JDBC stands for Java Database Connectivity. JDBC is a programming interface for Java that defines how a user can access to connect to a database using Java.

Who is a Scala Developer?

A Scala Developer is a person who has a high-level understanding of creating, maintaining and designing Scala Based Applications. 

Why are Scala Developers so well paid?

Scala is regarded as an emerging ability, which has seen a significant increase in demand over the previous five years. Thus there is a huge demand for Scala Developers in the industry.

Is Scala better than Java?

According to the study, Scala is quicker than Java. Typical developers can write code without too much thought given to optimization. Thus it can be concluded that Scala is better than Java.

What is the role of a Scala Developer?

Since clicking refresh is not counted as a time-out scenario, so as soon as the reload button is pressed, this causes the existing subclass objects to be replaced with new subclass objects. Thus there might rise a need to preserve the content on hitting refresh.

Conclusion

In this article, we discussed all about the twirl template engine. We also discussed the various dependencies in the twirl template engine. In the end, we further looked at various common use cases and the custom format for the twirl template engine. 

Hey Ninjas! Don’t stop here. Check out Coding Ninjas for Python, more unique courses, and guided paths. Also, check out our courses on DSA, and OOPS. Also, try Coding Ninjas Studio for more exciting articles, interview experiences, and excellent Machine Learning and Python problems. 

 

Live masterclass