Created
June 19, 2012 02:04
-
-
Save chrhicks/2951915 to your computer and use it in GitHub Desktop.
handlebars.scala from files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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