【问题标题】:How to allow certain HTML tags in a form field in Symfony 1.2如何在 Symfony 1.2 的表单字段中允许某些 HTML 标签
【发布时间】:2009-08-24 04:49:37
【问题描述】:

我正在玩 Symfony,但遇到了障碍。

我创建了一个模型“CmsPage”,它有一个名为“content”的字段,它存储为一个 clob(我相信这是特定于学说的)。当我创建应用程序时,我设置了“--escaping-strategy=on”,所以如果我在编辑使用 html 实体或类似内容编码的 CmsPage 时输入任何 html。我想在这个领域允许 html 并且快速谷歌搜索并没有太大帮助。也许我在搜索错误的术语。

任何我想禁用此字段的字符转义并可能只允许选择少量 html 标记的人。在 Symfony 中执行此操作的正确方法是什么?

【问题讨论】:

    标签: php forms symfony1


    【解决方案1】:

    您可以使用http://htmlpurifier.org/,它是满足您需求的绝佳工具。

    这里是 htmlpurifier 的小配置。这些规则与 TinyMce 编辑器完美匹配。

    $purifier = new HTMLPurifier();
    $purfier_config = HTMLPurifier_Config::createDefault();
    $purfier_config->set('HTML.DefinitionID', 'User Content Filter');
    $purfier_config->set('HTML.DefinitionRev', 1);
    // these are allowed html tags, means white list
    $purfier_config->set('HTML.Allowed', 'a,strong,em,p,span,img,li,ul,ol,sup,sub,small,big,code,blockquote,h1,h2,h3,h4,h5');
    // these are allowed html attributes, coool!
    $purfier_config->set('HTML.AllowedAttributes', 'a.href,a.title,span.style,span.class,span.id,p.style,img.src,img.style,img.alt,img.title,img.width,img.height');
    // auto link given url string
    $purfier_config->set('AutoFormat.Linkify', true);
    // auto format \r\n lines
    $purfier_config->set('AutoFormat.AutoParagraph', true);
    // clean empty tags
    $purfier_config->set('AutoFormat.RemoveEmpty', true);
    // cache dir, just for symfony of course, you can change to another path
    $purfier_config->set('Cache.SerializerPath', sfConfig::get('sf_cache_dir'));
    // translation type, 
    $purfier_config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
    // allow youtube videos
    $purfier_config->set('Filter.YouTube', true);
    $purfier_config->set('HTML.TidyLevel', 'heavy');
    // now clean your data
    $clean_nice_html_data = $purifier->purify($user_input_data, $purfier_config);
    

    现在您可以使用 html 标签将数据插入到数据库中,并且您不需要转义您的数据,因为 htmlpurifier 会为您清除肮脏、危险的数据,并且只接受您允许的标签和属性。

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      来自http://www.librosweb.es/symfony_1_1_en/capitulo7/output_escaping.html

      每个模板都可以访问一个 $sf_data 变量,它是一个引用所有转义变量的容器对象。 [跳过] $sf_data 还允许您访问未转义或原始数据。这在变量存储要由浏览器解释的 HTML 代码时很有用,前提是您信任该变量。需要输出原始数据时调用getRaw()方法。

      echo $sf_data->getRaw('test'); => alert(document.cookie)每次需要将包含 HTML 的变量真正解释为 HTML 时,您都必须访问原始数据。您现在可以理解为什么默认布局使用 $sf_data->getRaw('sf_content') 来包含模板,而不是更简单的 $sf_content,它会在激活输出转义时中断。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-25
        • 2013-12-25
        • 2017-07-29
        相关资源
        最近更新 更多