【问题标题】:How to properly enable the twig's sandbox extension in Symfony2?如何在 Symfony2 中正确启用树枝的沙箱扩展?
【发布时间】:2013-04-17 21:30:21
【问题描述】:

在 Symfony2 中,默认情况下禁用了一些 Twig 模块。其中之一是调试扩展,它添加了{% debug %} 标签(在开发环境中很有用)。

要启用它,没什么难的,您可以将此服务添加到您的配置中:

  debug.twig.extension:
    class: Twig_Extensions_Extension_Debug
    tags:
      - { name: 'twig.extension' }

但是如何启用{% sandbox %}标签呢?

我的问题是扩展的构造函数采用了安全策略:

public function __construct(Twig_Sandbox_SecurityPolicyInterface $policy, $sandboxed = false)
{
    $this->policy            = $policy;
    $this->sandboxedGlobally = $sandboxed;
}

通过阅读twig documentation,我看到了本地实现它的方法(没有 Symfony2):

$tags = array('if');
$filters = array('upper');
$methods = array(
    'Article' => array('getTitle', 'getBody'),
);
$properties = array(
    'Article' => array('title', 'body'),
);
$functions = array('range');
$policy = new Twig_Sandbox_SecurityPolicy($tags, $filters, $methods, $properties, $functions);
$sandbox = new Twig_Extension_Sandbox($policy);
$twig->addExtension($sandbox);

我可以在使用沙盒之前在服务中做类似的事情,但这不像我们习惯的依赖注入那么清楚。

在 Symfony2 中启用 twig 的沙箱扩展是否有更好/正确的方法?

【问题讨论】:

    标签: php symfony twig sandbox


    【解决方案1】:

    为什么不创建安全策略的私有服务:

    parameters:
        twig.sandbox.tags:
            - if
        twig.sandbox.filters:
            - upper
        twig.sandbox.methods:
            Article: [getTitle, getBody]
        twig.sandbox.properties:
            Article: [title, body]
        twig.sandbox.functions:
            - range
    
    twig.sandbox.policy:
        class: Twig_Sandbox_SecurityPolicy
        arguments:
            - %twig.sandbox.tags%
            - %twig.sandbox.filters%
            - %twig.sandbox.methods%
            - %twig.sandbox.properties%
            - %twig.sandbox.functions%
        public: false
    

    然后您可以将此服务注入twig.sandbox.extension 服务:

    twig.sandbox.extension:
        class: Twig_Extension_Sandbox
        arguments:
            - @twig.sandbox.policy
        tags:
            - { name: twig.extension }
    

    完成。将 twig.sandbox.policy 标记为私有可确保无法使用容器访问它(它仍然可以注入其他服务,但我认为这不是问题)。

    免责声明:我没有对此进行测试,它可能需要一些调整才能真正起作用,所以不要复制粘贴!

    【讨论】:

    • 嗨,你能提供更多关于这个答案的细节吗?我们在哪里编写“twig.sandbox.policy”和“twig.sandbox.extension”配置?谢谢!
    • 这应该在您的services.yml 配置中完成(在示例的情况下)。
    猜你喜欢
    • 1970-01-01
    • 2011-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多