2017-01-22 5 views
7

나는 후자를 사용하는 것을 선호하지만, Scalatags를 playframework에 통합하는 방법을 잘 모릅니다.Playframework : Twirl 대신 Scalatags 사용

이 내 간단한 레이아웃입니다 : 나는 그것을 렌더링하려고 방법

object Test 
{ 
    import scalatags.Text.all._ 
    def build = 
    { 

    html(
     head(
     title := "Test" 
    ), 
     body(

     h1("This is a Triumph"), 
     div(
      "Test" 
     ) 
    ) 
    ) 
    } 
} 

이것은 :

Ok(views.Test.build.render) 

문제가되지 HTML로, 나는 일반 문자열로 얻을 것이다.

물론 하나의 해결책은 단순히 추가하는 것입니다.

Ok(views.Test.build.render).as("text/html") 

하지만 실제로는 유일한 방법입니까? (도우미 메서드를 만들지 않고)

답변

9

Ok(views.Test.build)으로 전화를 걸 수 있다고 가정합니다. Play는 ScalaTags를 모르고 있으므로 something 여기에 직접 작성해야합니다.

Play는 HTTP 응답을 생성하기 위해 암시적인 기기를 사용합니다. Ok(...)으로 전화하면 play.api.mvc.Results 특성에 실제로 apply (으)로 전화하고 있습니다. 의는 서명을 살펴 보자 :

def apply[C](content: C)(implicit writeable: Writeable[C]): Result 

그래서 우리는 우리가 암시 Writeable[scalatags.Text.all.Tag]이 필요하다고 볼 수 있습니다

implicit def writeableOfTag(implicit codec: Codec): Writeable[Tag] = { 
    Writeable(tag => codec.encode("<!DOCTYPE html>\n" + tag.render)) 
} 

는 DOCTYPE 선언을 포함하는 것을 잊지 마십시오. ScalaTags가 제공하지 않습니다.

Writeable.apply을 호출 할 때 콘텐츠 형식을 결정하기 위해 다른 암시 적 코드가 필요합니다. 여기의 서명입니다 :

def apply[A](transform: A => ByteString)(implicit ct: ContentTypeOf[A]): Writeable[A] 

은 그럼 쓸 수 ContentTypeOf[Tag] 암시 :

implicit def contentTypeOfTag(implicit codec: Codec): ContentTypeOf[Tag] = { 
    ContentTypeOf[Tag](Some(ContentTypes.HTML)) 
} 

이것은 우리가이 캐릭터 세트를 포함 (암시 적 코덱의 호의) as("text/html") 명시 적으로 를 작성하는 것을 방지 할 수 있습니다 그 결과 Content-Type 헤더가 text/html; charset=utf-8이됩니다.

는 모두 함께 퍼팅 :

import play.api.http.{ ContentTypeOf, ContentTypes, Writeable } 
import play.api.mvc.Results.Ok 
import scalatags.Text.all._ 

def build: Tag = { 
    html(
    head(
     title := "Test" 
    ), 
    body(

     h1("This is a Triumph"), 
     div(
     "Test" 
    ) 
    ) 
) 
} 

implicit def contentTypeOfTag(implicit codec: Codec): ContentTypeOf[Tag] = { 
    ContentTypeOf[Tag](Some(ContentTypes.HTML)) 
} 

implicit def writeableOfTag(implicit codec: Codec): Writeable[Tag] = { 
    Writeable(tag => codec.encode("<!DOCTYPE html>\n" + tag.render)) 
} 

def foo = Action { implicit request => 
    Ok(build) 
} 

당신은 아마 편한 곳에 그 implicits을 감싸 다음 컨트롤러 (들)을 가져올.

+3

왜 twirl이 기본 템플릿 엔진입니까? scalatags가 더 단순 해 보입니다. – BlueSky