简体   繁体   English

从HAML中的html内容变量中提取纯文本

[英]Extracting plain text from an html content variable in HAML

I'm trying to extract the plain text from some HTML content in HAML. 我正在尝试从HAML中的某些HTML内容中提取纯文本。 For example, if I have this HTML in a variable called message.content: 例如,如果我在名为message.content的变量中包含此HTML:

Hi, this is a <strong>test</strong> message!

I have a HAML line like this: 我有这样的HAML行:

%p= message.content

And I want this as the output: 我希望这作为输出:

<p>
  Hi, this is a test message!
</p>

Is there any possible way I can do it? 有什么可行的方法吗? I have looked at != but it interprets the HTML, and also the :plain filter, but no luck. 我看过!=但是它可以解释HTML以及:plain过滤器,但是没有运气。 any help would be much appreciated, thanks! 任何帮助将不胜感激,谢谢!

I do not know a HAML helper for this purpose and you have to make use of an external helper or by using a RegExp. 我不知道为此目的使用HAML助手,因此您必须使用外部助手或RegExp。 I know RegExp is not really the tool of choice for HTML processing, but it works fine in simple cases: 我知道RegExp实际上并不是HTML处理的首选工具,但是在简单情况下它可以正常工作:

%p= message.content.replace(/<\/?\w+\/?>/g, '')

Since you added the hamlc tag and you might want this solution to work in the browser, you can use jQuery to extract the text content: 由于添加了hamlc标记,并且您可能希望此解决方案在浏览器中运行,因此可以使用jQuery提取文本内容:

%p= $(message.content).text()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM