在Freemarker模板中删除HTML标签 [英] Remove HTML tags in Freemarker Template
问题描述
我有一个freemarker模板,该模板在允许HTML的上下文中和不允许HTML的上下文中显示相同的字符串.
I've got a freemarker template that displays the same string in a context where HTML is allowed as well as a context where it is not.
Freemarker中是否有内置功能,可让我从字符串中完全删除HTML标签?
Is there a built-in in Freemarker that allows me to entirely remove HTML tags from a string?
以下模板(假设有内置的remove_html
)
The following template (assuming there was a built-in remove_html
)
<#ftl output_format="HTML"/>
<html>
<head>
<title>${page_title?remove_html}</title>
</head>
<body>
<h1>${page_title?no_esc}</h1>
</body>
</html>
和模型Collections.singletonMap("page_title", "A <strong>Strong</strong> Argument")
应该指向
<html>
<head>
<title>A Strong Argument</title>
</head>
<body>
<h1>A <strong>Strong</strong> Argument</h1>
</body>
</html>
使用内置的esc
会给我<title>A <strong>Strong</strong> Argument</title>
,这不是我想要的 .
Using the built-in esc
would give me <title>A <strong>Strong</strong> Argument</title>
instead, which is not what I am looking for.
是否有类似remove_html
的东西,或者我需要提供自己的东西? (例如,使用 OWASP的java-html-sanitizer .)
Is there something like remove_html
or do I need to provide my own? (Using OWASP's java-html-sanitizer, for instance.)
推荐答案
您可以使用带有"r"标志的Freemarker内置字符串替换功能来启用正则表达式.
You could use the Freemarker built-in string replace function with the "r" flag to enable regular expressions.
下面是一个简单的正则表达式,可以解决这个问题:
Here's a simple regexp that does the trick:
${page_title?replace('<[^>]+>','','r')}
请注意,如果您在正则表达式中使用反斜杠,则必须按如下所示对它们进行转义(人为删除空白的示例):
Note that if you use backslashes within the regular expression they must be escaped, as follows (contrived example that removes whitespace):
${page_title?replace('\\s+','','r')}
这篇关于在Freemarker模板中删除HTML标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!