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.web.servlet.view;
018
019import com.samskivert.mustache.Mustache;
020import com.samskivert.mustache.Mustache.Compiler;
021
022import org.springframework.web.servlet.ViewResolver;
023import org.springframework.web.servlet.view.AbstractTemplateViewResolver;
024import org.springframework.web.servlet.view.AbstractUrlBasedView;
025
026/**
027 * Spring MVC {@link ViewResolver} for Mustache.
028 *
029 * @author Brian Clozel
030 * @since 2.0.0
031 */
032public class MustacheViewResolver extends AbstractTemplateViewResolver {
033
034        private final Mustache.Compiler compiler;
035
036        private String charset;
037
038        /**
039         * Create a {@code MustacheViewResolver} backed by a default instance of a
040         * {@link Compiler}.
041         */
042        public MustacheViewResolver() {
043                this.compiler = Mustache.compiler();
044                setViewClass(requiredViewClass());
045        }
046
047        /**
048         * Create a {@code MustacheViewResolver} backed by a custom instance of a
049         * {@link Compiler}.
050         * @param compiler the Mustache compiler used to compile templates
051         */
052        public MustacheViewResolver(Compiler compiler) {
053                this.compiler = compiler;
054                setViewClass(requiredViewClass());
055        }
056
057        @Override
058        protected Class<?> requiredViewClass() {
059                return MustacheView.class;
060        }
061
062        /**
063         * Set the charset.
064         * @param charset the charset
065         */
066        public void setCharset(String charset) {
067                this.charset = charset;
068        }
069
070        @Override
071        protected AbstractUrlBasedView buildView(String viewName) throws Exception {
072                MustacheView view = (MustacheView) super.buildView(viewName);
073                view.setCompiler(this.compiler);
074                view.setCharset(this.charset);
075                return view;
076        }
077
078}