htmlhamlhamlc

Extracting plain text from an html content variable in HAML


I'm trying to extract the plain text from some HTML content in HAML. For example, if I have this HTML in a variable called message.content:

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

I have a HAML line like this:

%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. any help would be much appreciated, thanks!


Solution

  • 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. I know RegExp is not really the tool of choice for HTML processing, but it works fine in simple cases:

    %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:

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