Symfony 命令不起作用,因为它呈现模板

Symfony command doesn't work because it renders a template

我使用 Symfonies 生成了命令

php app/console generate:command

它生成了这个命令并添加了

class AppTriggerBuildCommand extends ContainerAwareCommand
{
protected function configure()
    {
        $this
            ->setName('trigger')
            ->setDescription('...')
            ->addArgument('argument', InputArgument::OPTIONAL, 'Argument description')
            ->addOption('option', null, InputOption::VALUE_NONE, 'Option description')
        ;
    }

protected function execute(InputInterface $input, OutputInterface $output)
{
    $argument = $input->getArgument('argument');
    if($argument == 'build'){
        $content = $this->pageAction('en', 'home');
        $this->storeContentElementsAction('en', 'home', $content);
    }

    $output->writeln('You are outside build.');
}


public function pageAction($language, $page) {
    $akeneo = $this->getContainer()
        ->get("pimc.akeneo_cms.backend_connector");

    $contentElements = $akeneo->getContentElementList($page);
    $contentElements = $this->sort($contentElements);
    $content = $this->getContainer()->get('templating')->renderResponse(
        'AppBundle::page.html.twig',
        ["contentElements" => $contentElements, "language" => $language]);

    return $content;

}

private function sort($contentElements) {
    ksort($contentElements);
    return $contentElements;
}

/**
 * @param $language
 * @param $page
 */
public function storeContentElementsAction($language, $page, \Symfony\Component\HttpFoundation\Response $content) {

    $staticalContent = new StaticContent();
    $staticalContent->setData($content->getContent());
    $staticalContent->setBuild(1);
    $staticalContent->setName("/".$language."/".$page.".html");

    $doctrine = $this->getContainer()->get('doctrine');
    $em = $doctrine->getManager();
    $em->persist($staticalContent);
    $em->flush();
}

}

StaticContent 是一个实体。

但是当我在命令行中调用这个命令时,出现了一个我无法解决的异常错误。 php app/console trigger build Symfony 给我这个错误行。

有人可以帮助我使这个命令对我有用吗?

您正在 pageAction 方法中操纵 HTTP Response,我认为您使用了错误的 twig 方法。

您似乎想将返回的 html 作为 html 字符串存储到您的数据库中。

正如 Cerad 在评论中指出的那样 为此,您只需调用 $content = $this->getContainer()->get('templating')->render($template, []);

现在 $content 是您呈现的 html 字符串。

PS:当你从另一个 'context' 那里 copy/paste 时,重新阅读你的代码 :D