This method is pretty long. Consider extracting methods for it. First candidate for extracting is code about live template in the end of the method.