如何在 symfony 中渲染来自服务 class 的视图?

How to render a view from service class in symfony?

我正在尝试在我的服务 class 中创建一个函数来呈现一个 twig 页面。我试过这样做: service.yml:

********
parameters:
    error.class: AppBundle\Utils\Error
services:
    app.error:
        class: '%error.class%'
        arguments: [@templating]

Error.php(服务 class):

****
class Error
{
    public function __construct($templating)
    {
        $this->templating = $templating;
    }

    public function redirectToError($condition,$message)
    {
        if($condition){
            return $this->templating->render('default/error.html.twig',array(
                'error_message' => $message,
            ));
        }
    }

}

error.html.twig有一些随机文本,看看它是否到达那里。

之后我从浏览器得到这个答案:

谁能告诉我这是什么问题?

YAML 在语法方面可能有点不确定,请确保使用所有 spaces(无制表符)。并确保每个缩进都是相同数量的 space 个字符。像每个级别的 2/4/6/8 或 4/8/12 等,如果你喜欢 4 宽。

您发布的代码应该没问题,但可能如上所述有些愚蠢。如果它实际上是文件中的错误部分/参数,symfony 应该会告诉您什么是意外的,因为它实际上会根据其内容验证 YAML 文件。


好吧 ['@templating'] 处理 YAML 解析错误,下一部分是如何使用服务。这是使用 service container.

完成的

在控制器中有一个别名,你可以这样做:

// required at the top to use the response class we use to return
use Symfony\Component\HttpFoundation\Response;

// in the action we use the service container alias
// short for $this->container->get('app.error');
$content = $this->get('app.error')->redirectToError(true, 'Hello world');
// as your redirectToError function returns a templating->render, which only returns a
// string containing the the rendered template, however symfony
// requires a Response class as its return argument.
// so we create a response object and add the content to it using its constructor
return new Response($content);

一些小东西:

$condition,可能会改变,如果不是,它似乎不应该在函数中,而是在函数调用周围,因为调用 redirectToError 似乎很奇怪,但没有错误,相反我们只是当我们确实有错误时调用它。

如果您要设置 class 变量来定义它 (details on visibility),建议使用:

class Error {
    // visibility public, private, protected 
    protected $templating;

你应该把 ' 放在 @templating

周围
services:
    app.error:
        class: AppBundle\Utils\Error
        arguments: ['@templating']