Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.github.edgarespina.mwa.view;
  
  import java.util.HashMap;
  import java.util.Map;
  
 
 
Publish one or more HTML templates as model attributes. Given a template directory:
   /templates
     a.html
     b.html
     /module
       a.html
 
If you want to publish the content of this directory as Spring model attributes, you need:
  new ModernViewResolver(
    new HtmlTemplates("/templates", " html");
  );
 
From the view you can access to a template by:
   <script type="text/html" id="superA">
      ${templates.a}
   </script>
 

Author(s):
edgar.espina
Since:
0.1
 
 public class HtmlTemplates extends AbstractModelContribution implements
     ServletContextAware {

  
Load templates from file system.

Author(s):
edgar.espina
Since:
0.5
 
   private interface TemplateLoader {

    
Returns templates as map instance.

Parameters:
directory Where we should look for? Required.
extension The template's extension. Required.
Returns:
A map with all the templates.
Throws:
java.io.IOException If a file cannot be read it.
 
     Map<StringObjectget(String directoryString extension)
         throws IOException;
   }

  
Load templates from the file system.

Author(s):
edgar.espina
Since:
0.5
 
   private class DefaultTemplateLoader implements TemplateLoader {

    
The lookup strategy.
 
     private ResourcePatternResolver resolver;

    
Creates a HtmlTemplates.DefaultTemplateLoader.

Parameters:
context The Servlet Context.
 
     public DefaultTemplateLoader(final ServletContext context) {
          new ServletContextResourceLoader(context));
    }

    
    @Override
    public Map<StringObjectget(final String directory,
        final String extensionthrows IOException {
      Map<StringObjectscope = new HashMap<StringObject>();
      Resource[] resources =
          .getResources(directory + "/**/*." + extension);
      for (Resource resource : resources) {
        String[] path = relativePath(directoryresource);
        // Read content.
        String content = Resources.toString(resource.getURL(), .);
        String filename = path[path.length - 1];
        String filenameNoExt =
            filename.substring(0,
                filename.length() - Files.getFileExtension(filename).length()
                    - 1);
        scope(scopepath).put(filenameNoExtcontent);
      }
      return scope;
    }

    
Creates a relative path.

Parameters:
directory The directory.
resource The resource.
Returns:
A relative path.
Throws:
java.io.IOException If the URI cannot be detected.
    private String[] relativePath(final String directory,
        final Resource resourcethrows IOException {
      String fullpath = resource.getURI().getPath();
      final String separator = "/";
      String relativePath = fullpath
          .substring(fullpath.indexOf(directory) + separator.length());
      // Make it relative.
      Iterable<Stringpath = Splitter.on(separator)
          .omitEmptyStrings()
          .trimResults()
          .split(relativePath);
      return Iterables.toArray(pathString.class);
    }

    
Return correct scope for the given path.

Parameters:
scope The root scope.
path The path of the template.
Returns:
The correct scope for the given path.
    private Map<StringObjectscope(final Map<StringObjectscope,
        final String[] path) {
      Map<StringObjectroot = scope;
      for (int i = 0; i < path.length - 1; i++) {
        @SuppressWarnings("unchecked")
        Map<StringObjectchild = (Map<StringObject>) root.get(path[i]);
        if (child == null) {
          child = new HashMap<StringObject>();
          root.put(path[i], child);
        }
        root = child;
      }
      return root;
    }
  }

  
Cache support for HtmlTemplates.TemplateLoader.

Author(s):
edgar.espina
Since:
0.5
  private class CacheTemplateLoader implements TemplateLoader {

    
Who is the man?
    private TemplateLoader loader;

    
The cache.
    private Map<StringObjectcache;

    
Creates a new HtmlTemplates.CacheTemplateLoader.

Parameters:
loader Who is the man?
    public CacheTemplateLoader(final TemplateLoader loader) {
      this. = loader;
    }

    
    @Override
    public Map<StringObjectget(final String directory,
        final String extension)
        throws IOException {
      if ( == null) {
         = .get(directoryextension);
      }
      return ;
    }
  }

  
Where are the templates?
  private String directory;

  
How they looks?
  private String extension;

  
The template loader.
  private TemplateLoader loader;

  
Creates a new HtmlTemplates model contribution.

Parameters:
directory Where are the templates (/temp, /templates, etc.)?
extension How they looks (html, mustache, etc.)?
  public HtmlTemplates(final String directoryfinal String extension) {
    Assert.notNull(directory"The template's directory is required.");
    Assert.isTrue(directory.length() > 0,
        "The template's directory is required.");
    Assert.notNull(extension"The template's directory is required.");
    Assert.isTrue(extension.length() > 0,
        "The template's directory is required.");
    this. = directory;
    this. = extension;
  }

  
  public void contribute(final HttpServletRequest request,
      final HttpServletResponse responsefinal ModelAndView modelAndView)
      throws IOException {
    modelAndView.getModel().putAll(.get());
  }

  
  public void setServletContext(final ServletContext context) {
    try {
      this. = new DefaultTemplateLoader(context);
      if (useCache()) {
        // Wrap the default loader and add cache support
        this. = new CacheTemplateLoader(this.);
        // hit and load the cache immediately
        this..get();
      }
    } catch (IOException ex) {
      throw new IllegalStateException("Unable to load templates."ex);
    }
  }
New to GrepCode? Check out our FAQ X