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

后端 未结 1 862
南笙
南笙 2021-01-15 11:02

In Symfony2, there is some Twig module disabled by default. One of them is the debug extension, that adds {% debug %} tag (useful on a development environment).

相关标签:
1条回答
  • 2021-01-15 11:41

    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!

    0 讨论(0)
提交回复
热议问题