Skip to content

Instantly share code, notes, and snippets.

@chrhicks
Created June 19, 2012 02:04
Show Gist options
  • Save chrhicks/2951915 to your computer and use it in GitHub Desktop.
Save chrhicks/2951915 to your computer and use it in GitHub Desktop.
handlebars.scala from files
object HandlebarsHelper {
def apply(baseuri: String): HandlebarsHelper = new HandlebarsHelper(baseuri)
}
class HandlebarsHelper(baseuri: String) extends Loggable {
val EXTENSION = ".handlebars"
def fromFile(fileName: String): Handlebars =
Handlebars(parse(getFileContents(baseuri + "/" + fileName).getOrElse("")))
private def getFileContents(path: String): Option[String] = {
val file = new File(path)
if (file.exists()) {
val source = Source.fromFile(path)
try
return Option(source.mkString)
finally
source.close()
}
warn("Could not parse file located at: " + path)
Option.empty
}
/**
* Recursively include partials. If the file cannot be found, do nothing.
* @param template
* @return
*/
private def parse(template: String): String = {
var combinedTemplate = template
val Partial = """\{\{>\s?(.*)\}\}""".r
Partial.findAllIn(template).foreach(p => p match {
case Partial(file) => {
getFileContents(baseuri + "/" + file + EXTENSION).map(contents => {
combinedTemplate = combinedTemplate.replaceAllLiterally(p, parse(contents))
})
}
})
combinedTemplate.toString()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment