Kategorien
Technical

Extend Jtwig with own resource

So the idea was to have a central template server which gives the templates then via json to the servlet who needs the data

Therefore we need to extend jtwig.

First, we need a TwigJsonResourceLoader that connects to somewhere and gets the result as stream. In the Example its a simple String

package bla;

import com.google.common.base.Optional;
import com.google.common.base.Supplier;
import org.jtwig.resource.loader.ResourceLoader;

import javax.servlet.ServletContext;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

import java.net.MalformedURLException;
import java.net.URL;

public class TwigJsonResourceLoader implements ResourceLoader {
    public static final String TYPE = "json";

    //private final Supplier<ServletContext> servletContextSupplier;

    public TwigJsonResourceLoader(){
    	//Supplier<ServletContext> servletContextSupplier) {
       // this.servletContextSupplier = servletContextSupplier;
    }

  @Override
    public Optional<Charset> getCharset(String path) {
        return Optional.absent();
    }

    @Override
    public InputStream load(String path) {
    
    	String initialString = "text";
    	InputStream targetStream = new ByteArrayInputStream(initialString.getBytes());
        return targetStream;
    }

    @Override
    public boolean exists(String path) {
        //try {
            return true; //servletContextSupplier.get().getResource(path) != null;
        //} catch (MalformedURLException e) {
        //    return false;
       // }
    }

    @Override
    public Optional<URL>  toUrl(String path) {
	    
        //try {
            //return Optional.of(servletContextSupplier.get().getResource(path));
            return Optional.absent();
        //} catch (MalformedURLException e) {
        //    return Optional.absent();
       // }
       
    }
}    

and then when we render, we add that resource to the environment

	EnvironmentConfiguration configuration = EnvironmentConfigurationBuilder.configuration()
				
				.resources()
				.relativeResourceResolvers().add(new ReferenceRelativeResourceResolver(Collections.singleton(TwigJsonResourceLoader.TYPE), RelativePathResolver.instance())).and()
			         .resourceLoaders().add(new TypedResourceLoader(TwigJsonResourceLoader.TYPE, new TwigJsonResourceLoader())).and()
		                .and()
				...
				.and().build();

...

			JtwigTemplate template = JtwigTemplate.classpathTemplate(templatename, configuration);

so that we can now include „json“ like this

{% include 'json:bla.twig' %}

which adds now


    <h1>this is how we scan</h1>

        {% include 'json:bla.twig' %}

results in


<h1>this is how we scan</h1>

    MyNameIsJson