mustache的默认分割符号为 {{ }}
当然也可以在模板文件的第一行添加 {{=<% %>}}
更多关于mustache的文档: http://mustache.github.io/mustache.5.html
将默认的{{}}分隔符替换为 <% %>
假如你不喜欢每个模板文件都添加这一行.我们应该可以修改默认的配置文件.
直接贴代码了.
主要是覆盖mustacheModule,重写里面的DefaultMustacheFactory中的compile与cache
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)
}
}
}
}