【问题标题】:Is there a way to get twig to consider a method of a passed object as safe?有没有办法让 twig 认为传递对象的方法是安全的?
【发布时间】:2012-10-17 16:46:56
【问题描述】:

在对传递到我的树枝模板的对象的方法调用中,树枝转义输出时遇到问题。我知道我可以使用|raw 过滤器解决这个问题,但希望有一种方法可以简单地在我的对象中指定某些方法是安全的,从而消除对原始过滤器的需求。

【问题讨论】:

    标签: symfony twig


    【解决方案1】:

    对象本身的方法调用不能保证 html 安全,因为普通对象/实体不(也不应该)知道模板引擎。

    但是,twig 过滤器或函数如果知道模板引擎并且可以在其定义中标记为 html 安全。

    所以你需要做的是实现一个html安全的twig过滤器来传递对象并在过滤器函数中调用你的对象的方法。

    我猜你的模板是这样的:

    <p>{{myObj.getHtmlRepresentation()|raw}}</p>
    

    现在你需要实现一个树枝过滤器并将模板更改为以下内容:

    <p>{{myObj|html_representation}}</p>
    

    树枝扩展应该是这样的:

    class MyTwigExtension {
    
        public function getFilters(){
           return array(
            // the magic is the is_safe=>html option
            'html_representation' => new \Twig_Filter_Method($this,'htmlRepresentation',array('is_safe'=>array('html'))),
        }
    
        public function htmlRepresentation($obj){
            return $obj->getHtmlRepresentation();
        }
    
     }
    

    一个设计考虑:如果您的对象是某种业务对象的实体,它不应该创建 html,但您应该将 html 创建移动到模板或树枝过滤器。

    【讨论】:

    • 一个有趣的问题解决方案。
    猜你喜欢
    • 2019-11-04
    • 2019-08-21
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    相关资源
    最近更新 更多