001/* 002 * Copyright 2012-2017 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.boot.autoconfigure.mustache; 018 019import java.io.InputStreamReader; 020import java.io.Reader; 021 022import com.samskivert.mustache.Mustache; 023import com.samskivert.mustache.Mustache.Compiler; 024import com.samskivert.mustache.Mustache.TemplateLoader; 025 026import org.springframework.context.ResourceLoaderAware; 027import org.springframework.core.io.DefaultResourceLoader; 028import org.springframework.core.io.Resource; 029import org.springframework.core.io.ResourceLoader; 030 031/** 032 * Mustache TemplateLoader implementation that uses a prefix, suffix and the Spring 033 * Resource abstraction to load a template from a file, classpath, URL etc. A 034 * {@link TemplateLoader} is needed in the {@link Compiler} when you want to render 035 * partials (i.e. tiles-like features). 036 * 037 * @author Dave Syer 038 * @since 1.2.2 039 * @see Mustache 040 * @see Resource 041 */ 042public class MustacheResourceTemplateLoader 043 implements TemplateLoader, ResourceLoaderAware { 044 045 private String prefix = ""; 046 047 private String suffix = ""; 048 049 private String charSet = "UTF-8"; 050 051 private ResourceLoader resourceLoader = new DefaultResourceLoader(); 052 053 public MustacheResourceTemplateLoader() { 054 } 055 056 public MustacheResourceTemplateLoader(String prefix, String suffix) { 057 this.prefix = prefix; 058 this.suffix = suffix; 059 } 060 061 /** 062 * Set the charset. 063 * @param charSet the charset 064 */ 065 public void setCharset(String charSet) { 066 this.charSet = charSet; 067 } 068 069 /** 070 * Set the resource loader. 071 * @param resourceLoader the resource loader 072 */ 073 @Override 074 public void setResourceLoader(ResourceLoader resourceLoader) { 075 this.resourceLoader = resourceLoader; 076 } 077 078 @Override 079 public Reader getTemplate(String name) throws Exception { 080 return new InputStreamReader(this.resourceLoader 081 .getResource(this.prefix + name + this.suffix).getInputStream(), 082 this.charSet); 083 } 084 085}