mustache的默认分割符号为 {{ }}html
固然也能够在模板文件的第一行添加 {{=<% %>}}java
更多关于mustache的文档: http://mustache.github.io/mustache.5.htmlgit
将默认的{{}}分隔符替换为 <% %>github
假如你不喜欢每一个模板文件都添加这一行.咱们应该能够修改默认的配置文件.web
直接贴代码了.缓存
主要是覆盖mustacheModule,重写里面的DefaultMustacheFactory中的compile与cacheide
package com.web_test.module import com.github.mustachejava._ import com.google.common.cache.{CacheLoader, LoadingCache, CacheBuilder} import com.google.inject.Provides import com.twitter.finatra.annotations.Flag import com.twitter.finatra.http.internal.marshalling.mustache.ScalaObjectHandler import com.twitter.finatra.http.modules.{LocalFilesystemDefaultMustacheFactory, DocRootModule} import com.twitter.finatra.http.modules.MustacheModule._ import com.twitter.finatra.http.routing.FileResolver import com.twitter.inject.TwitterModule import java.io._ import javax.inject.Singleton import scala.collection.mutable object myMustacheModule extends TwitterModule { private val templatesDir = flag("mustache.templates.dir", "templates", "templates resource directory") override def modules = Seq(DocRootModule) @Provides @Singleton def provideMustacheFactory( resolver: FileResolver, @Flag("local.doc.root") localDocRoot: String): MustacheFactory = { // templates are cached only if there is no local.doc.root // val cacheMustacheTemplates = localDocRoot.isEmpty val templatesDirectory = templatesDir() new DefaultMustacheFactory(templatesDirectory) { setObjectHandler(new ScalaObjectHandler) // 新建一个mp的mustache解析工具 // 使用 mp 覆盖 默认里面的 mc, 由于mc没法override,因此须要重写一个.而且在下面使用mp替换掉 val mp = new MustacheParser(this) { // 覆盖 override def compile(file: String): Mustache = { val reader: Reader = getReader(file) if (reader == null) { throw new MustacheNotFoundException(file) } compile(reader, file) // 调用下面的方法 } // 自定义解析符号. // 主要是第三个参数与第四个参数,默认的是{{和}} override def compile( reader: Reader, file : String): Mustache = { super.compile(reader,file,"<%","%>") } } // scala.concurrent. val cachex = new mutable.HashMap[String,Mustache]() // 初始化cacheLoader protected class MustacheCacheLoader extends CacheLoader[String, Mustache] { @throws(classOf[Exception]) override def load(key: String): Mustache = { mp.compile(key) } } // 为了可以从入口进入,须要覆盖 createMustacheCache // 里面会有cacheLoader,可是须要使用mp来自定义的标签. override def createMustacheCache: LoadingCache[String, Mustache] = { return CacheBuilder.newBuilder.build(new MustacheCacheLoader) } // 用于缓存cache的地方 override def compilePartial (template: String) : Mustache = { // cache 获取失败,则使用mp的compile 编译 ( 上面override里里面的自定义参数 ) cachex.get(template) match { case Some(item) => item case _ => { // 解析结果,存放到cachex里面 val mustache = mp.compile(template) cachex ++= Map(template -> mustache ) mustache.init mustache } } } // 便于调试代码 override def compile(name: String): Mustache = { super.compile(name) } } } }