How to properly enable the twig's sandbox extension in Symfony2?

假装没事ソ 提交于 2019-12-01 11:35:36
Ramon Kleiss

Why not create a private service of the security policy:

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

You can then inject this service into the twig.sandbox.extension service:

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

Done. Marking the twig.sandbox.policy private ensures it won't be accessible using the container (it can still be injected into other services, but I think that's not an issue).

Disclaimer: I haven't tested this and it probably needs some tweaking before it actually works so don't copy paste!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!