001package io.jstach.jstachio.formatters; 002 003import java.net.URI; 004import java.net.URL; 005 006import org.eclipse.jdt.annotation.Nullable; 007 008import io.jstach.jstache.JStacheFormatter; 009import io.jstach.jstache.JStacheFormatterTypes; 010import io.jstach.jstachio.Appender; 011import io.jstach.jstachio.Formatter; 012import io.jstach.jstachio.Output; 013 014/** 015 * Formatter that follows the spec rules that if a variable is <code>null</code> it will 016 * be an empty string (ie NOOP). 017 */ 018@JStacheFormatter 019@JStacheFormatterTypes(types = { URI.class, URL.class }) 020public interface SpecFormatter extends Formatter { 021 022 /** 023 * {@inheritDoc} 024 */ 025 @Override 026 default <A extends Output<E>, E extends Exception> void format(Appender downstream, A a, String path, Class<?> c, 027 @Nullable Object o) throws E { 028 if (o != null) { 029 downstream.append(a, String.valueOf(o)); 030 } 031 } 032 033 /** 034 * {@inheritDoc} <strong> Unlike the normal behavior of {@link String#valueOf(Object)} 035 * if a String is null then nothing will be rendered per the mustache spec. </strong>. 036 */ 037 @Override 038 default <A extends Output<E>, E extends Exception> void format(Appender downstream, A a, String path, 039 @Nullable String s) throws E { 040 if (s != null) { 041 downstream.append(a, s); 042 } 043 } 044 045 /** 046 * Provides the formatter for static lookup. 047 * @return the single instance of the spec formatter 048 */ 049 public static Formatter provider() { 050 return SpecFormatterSingleton.SPEC_FORMATTER; 051 } 052 053} 054 055enum SpecFormatterSingleton implements SpecFormatter { 056 057 SPEC_FORMATTER; 058 059}