Скорость Apache: существует ли стандартный способ проверить правильность шаблона из командной строки?

Наш веб-сайт использует язык шаблона Apache Velocity. Наша Система управления контентом уже проверяет любые сгенерированные XML-документы на отмеченность. Нас попросили проверить документы для ловли Скоростных синтаксических ошибок прежде, чем продвинуть файлы на живой сайт.

Существует ли стандартный способ проверить правильность шаблона Velocity из командной строки?

Я готов читать в пути к шаблону, инициализировать Скоростной Механизм, проанализировать шаблон и зафиксировать любые ошибки как показано на этой странице, но если существует готовый инструмент, который берет файл и конфигурацию, и выкладывает любые ошибки, затем я использовал бы это.


Обновление

Вот то, что я закончил тем, что делал:

package velocitysample;

import java.io.IOException;
import java.io.StringWriter;
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.MethodInvocationException;

public class Main
{
   /** Define a static logger variable so that it references the Logger
    *  instance named "MyApp".
    */
    private static Logger logger = Logger.getLogger(Main.class);


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {

        /* Set up a simple log4j configuration that logs on the console. */
        BasicConfigurator.configure();


        /* Check to see that a template path was passed on the command line. */
        if (args.length != 1)
        {
            logger.fatal("You must pass the path to a template as a " +
                    "command line argument.");
            return;
        }

        /* Pull the template filename from the command line argument. */
        String fileName = args[0];

        try
        {
            Velocity.setProperty("resource.loader", "file");
            Velocity.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
            Velocity.setProperty("file.resource.loader.path", "/templates/");
            Velocity.setProperty("file.resource.loader.cache", "false");
            Velocity.setProperty("file.resource.loader.modificationCheckInterval", "0");

            Velocity.init();
        }
        catch (Exception ex)
        {
            logger.fatal("Error initializing the Veolcity engine.", ex);
            return;
        }

        boolean error = false;

        /* Create an empty Velocity context */
        VelocityContext context = new VelocityContext();

        Template template = null;

        try
        {
           template = Velocity.getTemplate(fileName);
        }
        catch( ResourceNotFoundException rnfe )
        {
           logger.error("Couldn't find the template to parse at this path: " +
                   fileName + ".", rnfe);
           error = true;
        }
        catch( ParseErrorException peex )
        {
            logger.error("Error parsing the template located at this path: " +
                    fileName + ".", peex);
            error = true;
        }
        catch( MethodInvocationException mie )
        {
            logger.error("Something invoked in the template (" + fileName +
                    ") threw an Exception while parsing.", mie);
            error = true;
        }
        catch( Exception e )
        {
            logger.error("An unexpected exception was thrown when attempting " +
                    "to parse the template: " + fileName + ".", e);
            error = true;
        }

        if (error)
        {
            return;
        }

        StringWriter sw = new StringWriter();
        try
        {
            template.merge(context, sw);
        } 
        catch (ResourceNotFoundException rnfe)
        {
            logger.error("Couldn't find the template to merge at this path: " +
                   fileName + ".", rnfe);
            error = true;
        } 
        catch (ParseErrorException peex)
        {
            logger.error("Error parsing the template at this path during merge: " +
                    fileName + ".", peex);
            error = true;
        } 
        catch (MethodInvocationException mie)
        {
            logger.error("Something invoked in the template (" + fileName +
                    ") threw an Exception while merging.", mie);
            error = true;
        } 
        catch (IOException ioe)
        {
            logger.error("Error reading the template located at this path from " +
                    "disk: " + fileName + ".", ioe);
            error = true;
        }
        catch( Exception e )
        {
            logger.error("An unexpected exception was thrown when attempting " +
                    "to merge the template: " + fileName + ".", e);
            error = true;
        }

        if (!error)
        {
            logger.info("No syntax errors detected.");
        }
    }
}

6
задан braveterry 16 December 2009 в 17:46
поделиться

2 ответа

Вместе с Velocity поставляется инструмент TemplateTool, который выгружает все ссылки и может использоваться для проверки синтаксиса шаблона.

Однако вы должны правильно настроить контекст для проверки любого шаблона. Так что лучшая проверка - это написать свой собственный инструмент с вашим собственным контекстом.

4
ответ дан 17 December 2019 в 02:29
поделиться

Чтобы поймать синтаксические ошибки скоростей, ваш подход, вероятно, лучший.

Однако он будет игнорировать недействительные аргументы макроса и несуществующие ссылки. В VOLOCITITY 1.6 Существует строгий режим, который вы можете установить, который выброс исключение для параметров плохого макроса (например, неправильный номер) или для плохих ссылок (например, $ abc.Baxmethod ()). Это предполагает, что вы заполните контекст шаблонов, используемых в вашем инструменте тестирования, так же, как при использовании шаблонов в производстве.

1
ответ дан 17 December 2019 в 02:29
поделиться
Другие вопросы по тегам:

Похожие вопросы: