All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.rapidoid.integrate.JMustacheViewResolver Maven / Gradle / Ivy

There is a newer version: 5.5.5
Show newest version
package org.rapidoid.integrate;

import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import org.rapidoid.annotation.Authors;
import org.rapidoid.annotation.Since;
import org.rapidoid.http.View;
import org.rapidoid.http.customize.ResourceLoader;
import org.rapidoid.http.impl.AbstractViewResolver;

import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;

/*
 * #%L
 * rapidoid-integrate
 * %%
 * Copyright (C) 2014 - 2016 Nikolche Mihajlovski and contributors
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

/**
 * 

ViewResolver for samskivert's JMustache.
* To use this call {@code My.viewResolver(new JMustacheViewResolver());}

*

If you want to customize any compiler configurations do e.g.:

*
{@code
 *    JMustacheViewResolver resolver = new JMustacheViewResolver();
 *    resolver.setCustomizer(compiler -> compiler.defaultValue("N/A"));
 * }
*/ @Authors({"kormakur", "Nikolche Mihajlovski"}) @Since("5.2.0") public class JMustacheViewResolver extends AbstractViewResolver { @Override public View getView(String viewName, final ResourceLoader templateLoader) throws Exception { Mustache.TemplateLoader loader = loader(templateLoader); String template = new String(templateLoader.load(filename(viewName))); Mustache.Compiler compiler = getViewFactory(templateLoader); Template mustache = compiler.withLoader(loader).compile(template); return view(mustache); } @Override protected Mustache.Compiler createViewFactory(ResourceLoader templateLoader) { return Mustache.compiler().withLoader(loader(templateLoader)); } protected Mustache.TemplateLoader loader(final ResourceLoader templateLoader) { return new Mustache.TemplateLoader() { @Override public Reader getTemplate(String name) throws Exception { return new StringReader(new String(templateLoader.load(filename(name)))); } }; } protected View view(final Template mustache) { return new View() { @Override public void render(Object model, OutputStream out) { PrintWriter writer = new PrintWriter(out); mustache.execute(model, writer); writer.flush(); } }; } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy