0

What is the best waya to render or output Soy Templates from closure-templates to a browser?

Currently i have the following: package de.envisia.erp.web.servlet;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.template.soy.SoyFileSet;

import com.google.template.soy.tofu.SoyTofu;
/**
 * Servlet implementation class EntryPoint
 */
@WebServlet("/EntryPoint")
public class EntryPoint extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
 * @see HttpServlet#HttpServlet()
 */
public EntryPoint() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ServletContext servletContext = this.getServletContext();
    String pathContext = servletContext.getRealPath("/WEB-INF/");
    //response.getWriter().println(pathContext);

    SoyFileSet sfs = new SoyFileSet.Builder().add(new File(pathContext + "\\templates\\hello.soy")).build();
    SoyTofu tofu = sfs.compileToTofu();
    String out = tofu.newRenderer("hello.world").render();
    response.getWriter().println(out);
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    }

}

But i don't think it is a good practice to use the println or even print() method of the response object, are there any better ways?

Christian Schmitt
  • 837
  • 16
  • 47
  • why not use the write method. however, the weakness in your code lies in that you are compiling the template on each request, that is going to be extremely slow. – lennel Jun 12 '13 at 09:03

1 Answers1

2

Take a look at https://github.com/codedance/silken.

The basic idea is to make a special servlet and forward requests to it:

RequestDispatcher rd = getServletContext().getRequestDispatcher("/soy/products.boat.sailingBoatView");
rd.forward(req, resp);
kafeman
  • 31
  • 1
  • 2