Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass raw html to Play framework view?

Tags:

I'm trying to pass a simple URL to a view within a play framework app, however when passed as a string, the & in the url is changed to & which causes the URL to not work.

If I change the argument to Html, i.e @(url: Srting) to @(url: Html), then I get an error when I try to pass the url as string to view.render() method.

How can I convert the url into Html and pass it as that?

like image 835
Ali Avatar asked Feb 07 '13 03:02

Ali


People also ask

What is twirl template?

A type safe template engine based on Scala 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.

What is the meaning of raw HTML?

The Raw HTML Content Type allows you to manually enter HTML code as content on the page. This Content Type would be useful if you are knowledgeable in HTML and want full control over the content that is produced.

Which component is responsible for building play framework?

Play Framework is an open-source web application framework which follows the model–view–controller (MVC) architectural pattern. It is written in Scala and usable from other programming languages that are compiled to JVM bytecode, e.g. Java.

Which technique enables a fast coding workflow minimizes the number of characters and keystrokes required in a file?

Razor minimizes the number of characters and keystrokes required when writing a view template, and enables a fast, fluid coding workflow.


2 Answers

To prevent the default escaping that happens for dynamic content on views you need to wrap the String with @Html(String) function:

View:

@(url: String) <div class="myLink">    Go to: @Html(url) <br>    not to: @url </div> 

Controller:

public static Result displayLink(){    return ok(view.render("<a href='http://stackoverflow.com/'>Stack Overflow</a>")); } 

See The template engine page on the documentation for more info (specifically the "Escaping" section at the very bottom).

like image 167
estmatic Avatar answered Oct 02 '22 00:10

estmatic


If you want to render HTML content instead of displaying it as raw text, return the content .as("text/html"). Example:

WS.url("http://www.stackoverflow.com").get().map(resp => Ok(resp.body).as("text/html")) 
like image 22
Hanxue Avatar answered Oct 01 '22 23:10

Hanxue