All Downloads are FREE. Search and download functionalities are using the official Maven repository.

jove.notebook.components.Template.scala Maven / Gradle / Ivy

The newest version!
package jove.notebook.components

import java.nio.charset.Charset

import com.google.common.base.Charsets
import com.google.common.io.Resources
import com.hubspot.jinjava.Jinjava
import com.hubspot.jinjava.interpret.JinjavaInterpreter
import com.hubspot.jinjava.lib.fn.ELFunctionDefinition
import com.hubspot.jinjava.loader.ResourceLocator

import scala.collection.JavaConverters._

private abstract class TemplateServerHelper

private object TemplateServerHelper {
  var root = "/"
  val lock = new AnyRef
  def staticUrl(rel: String): String = s"${root}static/$rel"
  def staticUrlNoVersion(rel: String): String = staticUrl(rel) // ???
}

class Template(root: String) {

  private val templateResourceLocator = new ResourceLocator {
    def getString(fullName: String, encoding: Charset, interpreter: JinjavaInterpreter) =
      Resources.toString(getClass.getClassLoader getResource s"public/jupyter/templates/$fullName", encoding)
  }

  private lazy val jinjava = {
    val jinjava = new Jinjava

    jinjava setResourceLocator templateResourceLocator

    jinjava.getGlobalContext registerFunction {
      new ELFunctionDefinition(
        "",
        "static_url",
        classOf[TemplateServerHelper].getMethod("staticUrl", classOf[String])
      )
    }

    jinjava.getGlobalContext registerFunction {
      new ELFunctionDefinition(
        "",
        "static_url_no_version",
        classOf[TemplateServerHelper].getMethod("staticUrlNoVersion", classOf[String])
      )
    }

    jinjava
  }

  def apply(source: String): String =
    templateResourceLocator.getString(source, Charsets.UTF_8, null)

  def render(template: String, params: Map[String, AnyRef]): String =
    TemplateServerHelper.lock.synchronized {
      val prevRoot = TemplateServerHelper.root
      TemplateServerHelper.root = root

      val r = jinjava.render(template, params.asJava)

      TemplateServerHelper.root = prevRoot

      r
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy