2

I am trying to create a Play custom template to return json using Twirl and am unable to find any solid examples for the same. Is there any other way in play to render a view with JSON and implement deadbolt on views if not twirl templating?

wwkudu
  • 2,778
  • 3
  • 28
  • 41

1 Answers1

2

You can do this in Twirl without a problem. Have you seen the custom format guide? Also, take a look at play.twirl.api.Formats to see how XML, etc, is implemented.

For example, here's the implementation of Play's built-in XML Twirl format.

class Xml private (elements: immutable.Seq[Xml], text: String) extends BufferedContent[Xml](elements, text) {
  def this(text: String) = this(Nil, Formats.safe(text))
  def this(elements: immutable.Seq[Xml]) = this(elements, "")

  /**
   * Content type of XML (`application/xml`).
   */
  def contentType = MimeTypes.XML
}

/**
 * Helper for XML utility methods.
 */
object Xml {

  /**
   * Creates an XML fragment with initial content specified.
   */
  def apply(text: String): Xml = {
    new Xml(text)
  }

}

/**
 * Formatter for XML content.
 */
object XmlFormat extends Format[Xml] {

  /**
   * Creates an XML fragment.
   */
  def raw(text: String) = Xml(text)

  /**
   * Creates an escaped XML fragment.
   */
  def escape(text: String) = Xml(StringEscapeUtils.escapeXml11(text))

  /**
   * Generate an empty XML fragment
   */
  val empty: Xml = new Xml("")

  /**
   * Create an XML Fragment that holds other fragments.
   */
  def fill(elements: immutable.Seq[Xml]): Xml = new Xml(elements)
}

Because you can do this in Twirl, you can use the existing Deadbolt templates as they are. If you choose to go with a non-Twirl implementation, you can just re-implement the Deadbolt templates you need because all the logic is actually handled outside the templates. Take a look at be.objectify.deadbolt.java.ViewSupport or be.objectify.deadbolt.scala.ViewSupport - for example, the dynamic template just accepts some parameters and passes them directly to ViewSupport.

@if(viewSupport.dynamic(name, meta, handler, timeout(), request)) {
   @body
}
Steve Chaloner
  • 8,162
  • 1
  • 22
  • 38