How to pass raw html to Play framework view?

痴心易碎 提交于 2019-12-20 10:25:33

问题


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?


回答1:


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).




回答2:


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"))


来源:https://stackoverflow.com/questions/14743199/how-to-pass-raw-html-to-play-framework-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!