![](/img/trans.png)
[英]Symfony 5 bundle services.yaml - no extension able to load the configuration
[英]How to register a Twig Extension in services.yaml?
我將細枝與Symfony2一起使用,我的項目結構為:
/myprojectroot
/app
/config
services.yml
bootstrap.php
/src
/Foo
/Bar
/Util
myextension.php
我正在遵循本文檔來創建擴展,但是我發現它缺少有關名稱空間,路徑和注冊的詳細信息。 我也閱讀了詳細的文檔,但並沒有太大幫助。
services:
app.twig_extension: <---What is this line? Just a name?
class: AppBundle\Twig\AppExtension
public: false
tags:
- { name: twig.extension } <--- Should I ever change that?
我的擴展名定義為:
編輯:我根據傑森·羅馬的答案更正了我的getFunctions(),但錯誤仍然存在。
namespace Foo\Bar\Util;
class QrCodeHandler extends \Twig_Extension
{
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('genqr', 'generateQRcode'),
);
}
public function generateQRcode($data)
{
//snip code...
}
public function getName()
{
return 'qr_extension';
}
}
和我的services.yaml:
services:
qr_extension:
class: Foo\Bar\Util\QrCodeHandler
public: false
tags:
- { name: twig.extension }
bootstrap.php用以下代碼加載services.yml:
$services = $parser->parse(__DIR__ . '/config/services.yml');
if (isset($services['services']))
{
foreach ( $services['services'] as $name => $class )
{
$app['service.' . $name] = $app->share(function (Application $app) use($class) {
$service = new $class($app);
if (!$service instanceof ServiceInterface)
{
$errorMessage = get_class($service) . ' must implement ServiceInterface.';
$app['monolog']->addError($errorMessage);
throw new \Exception($errorMessage);
}
return $service;
});
}
}
我當然要問,因為我遇到了錯誤
Twig_Error_Syntax:函數“ genqr”不存在
所以我想知道怎么了 我想問題是我如何注冊它。
有人可以告訴我注冊碼的各個部分是什么,我應該使用它做什么?
您在錯誤地聲明您的自定義函數。 應該是這樣的:
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('genqr', array($this, 'generateQRcode')),
);
}
這樣可以確保從您的類中調用generateQRcode
方法。 關於您的其他問題:
services:
app.twig_extension: <---What is this line? Just a name?
是的,那只是服務的名稱。 只要確保此名稱是唯一的即可。
tags:
- { name: twig.extension } <--- Should I ever change that?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.