symfony2:如何从模板访问服务

时间:2012-11-06 02:52:23

标签: php symfony

如果我创建了一个服务,有没有办法从twig访问它,而不创建twig.extension?

2 个答案:

答案 0 :(得分:108)

您可以在config.yml中将服务设置为twig全局变量,例如

#app/config/config.yml
twig:
    globals:
        your_service: "@your_service"

template.html.twig文件中,您可以通过以下方式调用您的服务:

{{ your_service.someMethod(twig_variable) }}

请参阅here

答案 1 :(得分:0)

要在 Symfony 5 中做到这一点,首先你必须在 services.yaml 中声明服务,例如:

        App\Service\NavigationHelper:
        arguments:
            foo: bar

然后您可以在 Twig 中声明该服务以供其使用。为此,您必须将其作为变量添加到位于 packages/twig.yaml 中的 Yaml 文件的“全局”部分:

const a = {x:1, y:1, z:1};
const b = {x:2, y:2, z:2};

function reduceObjects<T extends {[key: string]: any}>(currentValue: T, previousValue: T): T {
    const result = Object.assign({}, previousValue) as T;

    for (const key of Object.keys(result)) {
        const prev = result[key];
        //           ^^^^^^^^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− why is this okay...
        const curr = currentValue[key];
        if (typeof prev === "number" && typeof curr === "number") {
            result[key] = prev + curr;
        //  ^^^^^^^^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− ...but this isn't?
        //                 "Type 'string' cannot be used to index type 'T'.(2536)"
        } else if (typeof prev === "string" && typeof curr === "string") {
            result[key] = prev + curr;
        //  ^^^^^^^^^^^ (same error here of course)
        }
    }

    return result;
}

const c = reduceObjects(a, b);

现在您可以使用模板中的服务方法,就像 Mun Mun Das 在他的最后一段代码中建议的那样。