Skip to content

Embed static content into Scala at compile time

Notifications You must be signed in to change notification settings

passivsystems/embed

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Embed

Scala macro for embedding file content directly into a scala source file at compile time.

Add to sbt project

add the following to build.sbt:

libraryDependencies += "com.github.passivsystems" % "embed" % "0.0.1"
resolvers += "jitpack" at "https://jitpack.io"

Usage

first import the macro:

import com.passivsystems.embed.Embed._

then can reference any file with a path relative to the current source file:

val text: String = embed("resource.txt")

String interpolation

By using the sEmbed, we can have similar semantics to s"" String interpolation. The embedded file can refer to any variable in scope at the point of call.

Note, that the curly braces are required for all embedded expressions. e.g. ${myVal} not $myVal

e.g.

val guard = true
val txt = sEmbed("template.txt")

where template.txt:

the guard is: ${if (guard) "TRUE" else "FALSE"}

Scala js

One possible usecase is in Scala js projects to move html into their own file. e.g.

import com.passivsystems.embed.Embed._
import org.scalajs.dom
def el[T <: dom.raw.Element](id: String) =
    dom.document.getElementById(id).asInstanceOf[T]

val btnId = "uniqueId"
// el[dom.raw.HTMLElement]("div").innerHTML = s"""
// <button id="${btnId}">Click me</button>
// """
el[dom.raw.HTMLElement]("div").innerHTML = sEmbed("button.html")
el[dom.raw.HTMLButtonElement](btnId).onclick = { event: MouseEvent => println("Clicked!") }

where button.html:

<button id="${btnId}">Click me</button>

About

Embed static content into Scala at compile time

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages