Scala/Play: load template dynamically

Error processing SSI file

Answers

  1. Knox

    • 2020/9/11

    Based on @Nilanjan answer and for play-2.4 scala-2.11.7

      def page(page: String) = Action.async { implicit request =>
        Future.successful(Ok(loadTemplate(page)))
      }
    
      import reflect.runtime.universe._
      import play.api._
      import play.twirl.api.Html
      val currentMirror = runtimeMirror(Play.current.classloader)
      val packageName = "views.html."
      private def loadTemplate(name: String) = {
        val templateName = packageName + name
        val moduleMirror = currentMirror.reflectModule(currentMirror.staticModule(templateName))
        val methodSymbol = moduleMirror.symbol.info.member(TermName("apply")).asMethod
        val instanceMirror = currentMirror.reflect(moduleMirror.instance)
        val methodMirror = instanceMirror.reflectMethod(methodSymbol)
        methodMirror.apply().asInstanceOf[Html]
      }
    
  2. Angel

    • 2016/5/9

    Twirl can also be used outside of Play. An sbt plugin is provided for easy integration with Scala or Java projects. sbt-twirl requires sbt 1.3.0 or higher. To 

  3. Simon

    • 2015/1/16

    This template generates a Play Scala project name [play-scala-seed]: In this example, we are going to name it “baeldung-play-framework.” The organization name is going to be used as the package name. Scala package names follow the same convention as Java package names. Therefore, our package name will be “baeldung.com“.

  4. Larry

    • 2016/2/29

    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 

  5. Paul

    • 2017/3/3

    It's not quite good idea to allow search view by any text (for security reasons) as such can be passed in param, instead, you can resolve this quite easy with match statement - it will allow you restrict request to allowed views only and will handle wrong requests as well, probably Scala geeks can demonstrate nicer code, but this will work for you out of the box:

    def loadTemplate(templateName: String) = Action {
    
      templateName match {
        case "about" => Ok(about())
        case "home" => Ok(home())
        case "contact" => Ok(contact())
        case _ => NotFound(notFoundView())
      }
    
    }
    

    route:

    GET  /load-template/:templateName   controllers.Application.loadTemplate(templateName)
    

    Additional benefit is that you can grab additional data from request and pass it to the resolved view depending on templateName param

  6. Dupont

    • 2017/8/5

    Standard Playwriting Format Please follow these standard formatting rules: Act and Scene headings are centered. Character’s names are centered and capitalized.

  7. Adam

    • 2021/7/30

    https://playframework.com › documentation › ScalaHome

  8. Briggs

    • 2016/8/18

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

  9. Conner

    • 2020/9/14

    Here we go again! @Nilanjan answer adopted to Scala 2.12 and Play 2.6 (as moving to DI play.api.Play.current, TermName and declaration have been deprecated). For app, I had to use injector because @Inject()(app: Application) was causing circular dependency

    class HomeController @Inject()(injector: Injector, cc: ControllerComponents) extends AbstractController(cc) {
      def index(name: String = "index") = Action { implicit request: Request[AnyContent] =>
        import reflect.runtime.universe._
    
        val app = injector.instanceOf[Application]
        val currentMirror = runtimeMirror(app.classloader)
        val packageName = "views.html."
    
        val templateName = packageName + name
    
        val moduleMirror = currentMirror.reflectModule(currentMirror.staticModule(templateName))
        val methodSymbol = moduleMirror.symbol.typeSignature.decl(TermName("apply")).asMethod
    
        val instanceMirror = currentMirror.reflect(moduleMirror.instance)
        val methodMirror = instanceMirror.reflectMethod(methodSymbol)
    
        Ok(methodMirror.apply("some", "content").asInstanceOf[Html])
      }
    }
    
  10. Bentlee

    • 2020/3/8

    Play Scala Starter Template (ideal for new users!) - playframework/play-scala-starter-example

  11. Julien

    • 2015/8/19

    As stated in the Play documentation you can use the @defining helper. @​defining(if (event.getSeverity > 0) "green" else "red") { color => <div 

  12. Lane

    • 2019/9/11

    It provides different given template and automation to start play with the code from a rich and solid structure. the play framework 2.3.0 from the official play!framework website. We will also

  13. Jakari

    • 2019/12/20

    In your Template file

    general_template.scala.html

    @(templateName : String = "none")
    
    @templateName match {       
    
     case "about" => { //html elements}
    
     case "home" => {//html elements}
    
     case "contact" => {//html elements}
    
     case _ => { }
    
    }
    

    and in your controller

    def loadTemplate(templateName) = Action {
        Ok(views.html.general_template(templateName))
    }
    
  14. Ezekiel

    • 2016/11/19

    The Play framework Scala template engine, stand-alone and packaged as an SBT The _Twirl_ SBT plugin smoothly integrates templating support into your 

  15. Eduardo

    • 2020/3/11

    Outputs a complete commenting form for use within a template.

  16. Lorenzo

    • 2019/2/12

    player : the player currently viewing the page; group : the group the current player belongs to comment %} This is a multi-line comment {% endcomment %} 

  17. Krew

    • 2016/1/30

    Using scala reflection:

    object Application extends Controller {
    
      import reflect.runtime.universe._
      val currentMirror = runtimeMirror(Play.current.classloader)
      val packageName = "views.html."
    
      def index(name: String) = Action {
        val templateName = packageName + name
    
        val moduleMirror = currentMirror.reflectModule(currentMirror.staticModule(templateName))
        val methodSymbol = moduleMirror.symbol.typeSignature.declaration(newTermName("apply")).asMethod
    
        val instanceMirror = currentMirror.reflect(moduleMirror.instance)    
        val methodMirror = instanceMirror.reflectMethod(methodSymbol)
    
        Ok(methodMirror.apply().asInstanceOf[Html])
     }
    
     }
    
  18. George

    • 2019/9/24

    Configuring the Play 2.1 web application for Scala IDE. Now that the Play application is running, it needs to be configured so it can be imported into Scala IDE. Play 2.1 integrates sbteclipse, which allow to create configuration files of a project for Eclipse. First, exit the ‘run’ mode in Play using ctrl-d.

  19. Reign

    • 2019/10/24

    Composition with Mixins · Higher-order Functions · Nested Methods · Multiple Parameter Lists (Currying) · Case Classes · Pattern Matching · Singleton Objects​ 

  20. Maxwell

    • 2020/2/1

    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.

  21. James

    • 2019/5/25

    ↰ Play Framework [deprecated].

  22. Hank

    • 2019/12/25

    Play Framework Build Tools Play is a series of libraries available in Maven Repository, so you can use any Java build tool to build a Play project. However, much of the development experience Play is known for (routes, templates compilation and auto-reloading) is provided by sbt or Gradle.

  23. Jaxxon

    • 2015/4/20

    It seems that we cannot place import statement in scala templates and. I have to put import statements within the function like: @(map1: java.util.

  24. Yousef

    • 2020/5/25

  25. Christopher

    • 2020/1/24

    I've recently started using Dispatch, a bit arcane (great general intro, serious lack of detailed scenario/use-case based docs).Dispatch 0.9.1 is a Scala wrapper around Ning's Async Http Client; to fully understand what going on requires introducing one's self to that library.

  26. Ameer

    • 2017/12/19

    html, you may want to get or set variables between Scala and JavaScript. Here are some examples. set a scala variable. @test = { "something" } 

  27. Darius

    • 2020/7/28

    This template generates a Play Scala project name [play-scala-seed]: In this example, we are going to name it “baeldung-play-framework.” The organization name is going to be used as the package name. Scala package names follow the same convention as Java package names. Therefore, our package name will be “baeldung.com“.

  28. Harrison

    • 2020/10/27

  29. Cain

    • 2020/6/15

    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.

  30. Hysi

    • 2016/9/3

    The last comment before the constructor is used as the comment for the constructor in the If I have a view called user.scala.html that uses buildTree.​scala.html.

  31. Beckham

    • 2017/10/1

    Scala has both functions and methods and we use the terms method and function interchangeably with a minor difference. A Scala method is a part of a class which has a name, a signature, optionally some annotations, and some bytecode where as a function in Scala is a complete object which can be assigned to a variable.

  32. Sonny

    • 2015/5/4

    Scalatags of course. You can use it in any way you'd like: Scala, ScalaJS, render them dinamically(e.g. in Play server), statically (sbt- 

  33. Dangelo

    • 2021/9/16

    scala-seed is the official template for a “minimal” Scala project, but it’s definitely not the only one out there. Giter8 support Giter8 is a templating project originally started by Nathan Hamblen in 2010, and now maintained by the foundweekends project.

  34. Michael

    • 2021/5/31

    You are viewing the documentation for Play 1. The documentation for Play 2 is 

  35. Joshua

    • 2017/9/4

    Unlike normal functions, a template function will not be type-checked until using it​. Thus it does not raise a type error on x > y because the real types of x and y 

  36. Kylen

    • 2019/1/28

    This template generates a Play Scala project name [play-scala-seed]: In this example, we are going to name it “baeldung-play-framework.” The organization name is going to be used as the package name. Scala package names follow the same convention as Java package names. Therefore, our package name will be “baeldung.com“.

  37. Nikolas

    • 2017/12/23

    Written in

  38. Kaden

    • 2019/9/26

    Learning Scala with Play. Life's too short to not learn Scala. The Play Scala 

  39. Parisi

    • 2019/9/8

    Play 2.0 comes with a new and really powerful Scala-based template engine. their existing Scala language skills, and deliver a template markup syntax that 

  40. Andre

    • 2017/8/16

    play is in reality. The more fantastic the setting, the more description it will need. If your play has a particularly complex structure, you can also include a scene breakdown, either on this page or the next, as in the example below.) ACT I Scene 1 An office. Now. Scene 2 A small office. Last week. ACT II Scene 1 An office. Now.

Comments are closed.

More Posts