gpt4 book ai didi

symfony - 如何从 symfony 中的服务类渲染 View ?

转载 作者:行者123 更新时间:2023-12-03 23:16:43 26 4
gpt4 key购买 nike

我正在尝试在我的服务类中创建一个函数,该函数呈现一个 Twig 页面。我试过这样做:服务.yml:

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

Error.php(服务类):

****
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 有一些随机文本以查看它是否到达那里。

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

enter image description here

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

最佳答案

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

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


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

在 Controller 中有一个别名,你可以这样做:

// 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 似乎很奇怪,但没有错误,而是我们只是在遇到错误时调用它。

如果您要设置一个类变量来定义它 ( details on visibility ),建议这样做:

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

关于symfony - 如何从 symfony 中的服务类渲染 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44344624/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com