Templates used in java

§The template engine

Play comes with Twirl, a powerful Scala-based template engine, whose design was inspired by ASP.NET Razor. Specifically it is:

  • compact, expressive, and fluid: it minimizes the number of characters and keystrokes required in a file, and enables a fast, fluid coding workflow. Unlike most template syntaxes, you do not need to interrupt your coding to explicitly denote server blocks within your HTML. The parser is smart enough to infer this from your code. This enables a really compact and expressive syntax which is clean, fast and fun to type.
  • easy to learn: it allows you to quickly become productive, with a minimum of concepts. You use simple Scala constructs and all your existing HTML skills.
  • not a new language: we consciously chose not to create a new language. Instead we wanted to enable Scala developers to use their existing Scala language skills, and deliver a template markup syntax that enables an awesome HTML construction workflow.
  • editable in any text editor: it doesn’t require a specific tool and enables you to be productive in any plain old text editor.

Note: Even though the template engine uses Scala as expression language, this is not a problem for Java developers. You can almost use it as if the language were Java.

Remember that a template is not a place to write complex logic. You don’t have to write complicated Scala code here. Most of the time you will just access data from your model objects, as follows:

myUser.getProfile().getUsername() 

Parameter types are specified using a suffix syntax. Generic types are specified using the [] symbols instead of the usual <> Java syntax. For example, you write List[String] , which is the same as List in Java.

Читайте также:  Метод describe в python

Templates are compiled, so you will see any errors in your browser:

§Overview

A Play Scala template is a simple text file that contains small blocks of Scala code. Templates can generate any text-based format, such as HTML, XML or CSV.

The template system has been designed to feel comfortable to those used to working with HTML, allowing front-end developers to easily work with the templates.

Templates are compiled as standard Scala functions, following a simple naming convention. If you create a views/Application/index.scala.html template file, it will generate a views.html.Application.index class that has a render() method.

For example, here is a simple template:

You can then call this from any Java code as you would normally call a method on a class:

Content html = views.html.Application.index.render(customer, orders); 

§Syntax: the magic ‘@’ character

The Scala template uses @ as the single special character. Every time this character is encountered, it indicates the beginning of a dynamic statement. You are not required to explicitly close the code block — the end of the dynamic statement will be inferred from your code:

Hello @customer.getName()! ^^^^^^^^^^^^^^^^^^ Dynamic code 

Because the template engine automatically detects the end of your code block by analysing your code, this syntax only supports simple statements. If you want to insert a multi-token statement, explicitly mark it using brackets:

Hello @(customer.getFirstName() + customer.getLastName())! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Dynamic Code 

Note: Make sure not to include whitespaces between keywords of dynamic statements and parentheses.

For example, the following code doesn’t work:

@for (menu // Compilation error: '(' expected but ')' found. ^ 

You can also use curly brackets, to write a multi-statement block:

Because @ is a special character, you’ll sometimes need to escape it. Do this by using @@ :

My email is bob@@example.com 

§Template parameters

A template is like a function, so it needs parameters, which must be declared at the top of the template file:

@(customer: models.Customer, orders: List[models.Order]) 

You can also use default values for parameters:

Or even several parameter groups:

§Template constructor

By default, a template is generated as a static function that can be invoked in any context. If your template has dependencies on components, such as the messages API, you may find it easier to inject it with the components (and other templates) that it needs, and then you can inject that template into the controllers that use it.

Twirl supports declaring a constructor for templates, using @this() syntax at the start of the file, before the template parameters. The arguments to the constructor can be defined in the same way as the template parameters:

@this(messagesApi: MessagesApi) @(customer: models.Customer, orders: List[models.Order]) 

§Iterating

You can use the for keyword, in a pretty standard way:

§If-blocks

If-blocks are nothing special. Simply use Scala’s standard if statement:

@if(items.isEmpty()) < 

Nothing to display

> else <

@items.size() items!

>

§Declaring reusable blocks

You can create reusable code blocks:

Note that you can also declare reusable pure code blocks:

@title(text: String) = @ < text.split(' ').map(_.capitalize).mkString(" ") >

@title("hello world")

Note: Declaring code block this way in a template can be sometime useful but keep in mind that a template is not the best place to write complex logic. It is often better to externalize these kind of code in a Java class (that you can store under the views/ package as well if you want).

By convention a reusable block defined with a name starting with implicit will be marked as implicit :

§Declaring reusable values

You can define scoped values using the defining helper:

@defining(user.getFirstName() + " " + user.getLastName()) < fullName =>
Hello @fullName
>

§Import statements

You can import whatever you want at the beginning of your template (or sub-template):

@(customer: models.Customer, orders: List[models.Order]) @import utils._ . 

To make an absolute resolution, use root prefix in the import statement.

@import _root_.company.product.core._ 

If you have common imports, which you need in all templates, you can declare in build.sbt

TwirlKeys.templateImports += "org.abc.backend._" 

§Comments

You can write server side block comments in templates using @* *@ :

You can put a comment on the first line to document your template into the Scala API doc:

@************************************* * Home page. * * * * @param msg The message to display * *************************************@ @(msg: String) 

@msg

§Escaping

By default, dynamic content parts are escaped according to the template type’s (e.g. HTML or XML) rules. If you want to output a raw content fragment, wrap it in the template content type

Note: When using this feature, consider the security implications of outputting raw HTML if there is any possibility that the user can control the content. This technique is a common cause of Cross Site Scripting (XSS) vulnerabilities and is dangerous if not used with caution.

For example to output raw HTML:

Found an error in this documentation? The source code for this page can be found here. After reading the documentation guidelines, please feel free to contribute a pull request. Have questions or advice to share? Go to our community forums to start a conversation with the community.

Community support

Источник

Java String Templates [JEP-430]

In Java, we can create string templates containing embedded expressions (evaluated at runtime). Similar to other programming languages, Java template strings can include variables, methods or fields, computed at run time, to produce a formatted string as output.

String Templates (JEP-430) is a preview feature in Java 21.

1. What is a String Template?

Template string is a familiar feature that is present in most programming languages such as typescript template strings or angular interpolation. Basically, we embed the variables into a String and the values of the variables are resolved in runtime. Thus template strings produce different results for different values of the variables.

"Greetings >!"; //Angular `Greetings $< name >!`; //Typescript $"Greetings < name >!" //Visual basic f"Greetings < name >!" //Python

All the above templates will produce the same result in runtime for the same value of the variable ‘ name ‘. JEP-430 is a similar move to support template strings in Java.

String message = STR."Greetings \< name >!"; //Java

2. String Templates in Java

2.1. Traditional Approaches

String formatting is not new in Java. Traditionally, programmers have been different ways to produce formatted strings such as string concatenation , StringBuilder , String.format() and MessageFormat class.

//concatenation message = "Greetings " + name + "!"; //String.format() message = String.format("Greetings %s!", name); //concatenation //MessageFormat message = new MessageFormat("Greetings !").format(name); //StringBuilder message = new StringBuilder().append("Greetings ").append(name).append("!").toString();

All of the above approaches work but with drawbacks. Either they create code hard to read or they are just too verbose for a simple task.

Taking inspiration from other languages, Java plans to support template expressions that can perform string interpolation in runtime. The only difference is that Java approach is less prone to introducing security vulnerabilities specially in string values used in SQL statements, XML nodes etc.

Syntactically, a template expression resembles a string literal with a prefix.

String message = STR."Greetings \!";

In the above template expression:

  • STR is the template processor.
  • There is a dot operator (.) between the processor and the expression.
  • Template string with embedded expression. The expression is in form of ( \ ).

The result of the template processor, and thus the result of evaluating the template expression, is often a String — though not always.

Currently, Java supports 3 template processors:

  • STR: performs the standard interpolation.
  • FMT: performs interpolation, as well as interprets the format specifiers (defined in a href=”https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Formatter.html”) which appear to the left of embedded expressions
  • RAW: is a standard template processor that produces an unprocessed StringTemplate object.
String name = "Lokesh"; //STR String message = STR."Greetings \."; //FMT String message = STR."Greetings %-12s\."; //RAW StringTemplate st = RAW."Greetings \."; String message = STR.process(st);

4.1. Template Processor is Imported in Every Class

STR is a template processor and part of the language itself. It is a ‘ public static final ‘ field that is automatically imported into every Java source file so we can it directly. There is no need to import it.

4.2. Expressions support Variables, Member Fields and Methods

We can use local variables, static/non-static fields and even methods as the embedded expressions. Their values are computed at runtime.

//variable message = STR."Greetings \!"; //method message = STR."Greetings \!"; //field message = STR."Greetings \!";

4.3. Arithmetic is supported inside expressions

We can perform calculations and print the result in the same expression.

int x = 10, y = 20; String s = STR."\ + \ = \"; //"10 + 20 = 30"

4.4. Double quotes are supported without escape

As opposed to any other feature in Java, we can include double quotes without escaping in template strings. It provides very much-needed readability in Java strings.

String name = "Alex"; String msg = STR."The first name is \ exists in the "SQL Database"."; //produces - The first name is Alex exists in the "SQL Database".

4.5. Multi-line expressions are allowed

To improve readability, we can break an embedded expression into multiple lines. It is very much like nested method calls in builder pattern style code.

String time = STR."The current time is \< //sample comment - current time in HH:mm:ss DateTimeFormatter .ofPattern("HH:mm:ss") .format(LocalTime.now()) >.";

This Java tutorial discusses string templates in Java which is a new addition to the language in Java 21 as a preview feature. Keep watching for Java release notes for more changes to this feature.

Источник

Оцените статью