根据https://symfony.com/doc/current/html_sanitizer.html#allow-elements
我创建了一个html sanitizer实现:
- config/packages/html_sanitizer.yaml
framework:
html_sanitizer:
sanitizers:
app.post_sanitizer:
allow_safe_elements: true
#allow_static_elements: true
allow_elements:
img: '*'
#img: ['src', 'class']
span: '*'
p: 'class'
- Controller /TestController.php
#[Route('/read_html', name: 'read_html')]
public function readHtml(HtmlSanitizerInterface $appPostSanitizer): Response {
$testHtml = '<div>
<span style="font-size: 21pt;">This some big text</span>
<img src="img_girl.jpg" alt="Girl in a jacket" width="500" height="600" class="img-fluid" >
<p class="text-danger">this is some red text in bootstrap!</p>
</div>';
$testHtml2 = $appPostSanitizer->sanitize($testHtml);
dd($testHtml, $testHtml2);
}
- 输出:
"""
<div>
<span style="font-size: 21pt;">This some big text</span>
<img alt="Girl in a jacket" width="500" height="600" class="img-fluid" />
<p class="text-danger">this is some red text in bootstrap!</p>
</div>
"""
即除了 img
标记中的 src
之外,其他一切都有效。
src="img_girl.jpg"
缺失。
我尝试了任何我能想到的组合:img: ['src', 'class']
img: 'src'
。
清理后仍然无法使 src 显示。
最佳答案
您必须设置allow_relative_medias: true
。
当您将 allow_relative_medias
设置为 true
时,您指示清理程序对相对 URL 进行异常(exception)处理。相对 URL 是不包含完整网址和协议(protocol)的 URL(例如 img_girl.jpg
)。
在文档中了解更多信息:https://symfony.com/doc/current/html_sanitizer.html#force-allow-media-urls
关于php - 无法允许元素(img : 'src' ) with symfony html-sanitizer (symfony6. 3 php 8.2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77077353/