2
votes

I have some content in database table (blog post) that is trusted content and I want to display on screen. This content is HTML and has some code samples using Prism.js for syntax highlighting. Because of the HTML econding on a gsp page I need to use the raw method to output the content as is

${raw(post.content)}

This works great except for when I get to the code that is wrapped in a tags for my code samples. Instead of showing it as code its outputting the raw html which is not what I want. I somehow need to encode the text that is inside of there because If I don't I end up with something that looks like this.

enter image description here

I know that I could do the encoding on save but I already have hundreds of posts where this is not the case. Any ideas?

1
I'm not sure but can you try ${post.teaser.encodeAsHTML()} - JavaDev
the entire post is the ${post.content} what you are seeing there is a subset of that post - a code example from another blog post <pre><code class="language-html"> a bunch of markup here ${raw(post.teaser)} </code></pre> - Dan Vega
This is what the blog post looks like in the database and you can see from the picture above how its rendering. gist.github.com/cfaddict/9912759 - Dan Vega
I'm guessing what needs to happen is take the content and pass it to a service function that will look to see if anything needs to be encoded. If it finds any <code> tags use some regex to find/replace any content between those tags with encoded content. I suck at regex, this should be fun. - Dan Vega
@haventchecked posted... please let me know if that helps. sorry I totally forgot to post this :) - Dan Vega

1 Answers

8
votes

In my case I had to grab the raw content in the view

${raw(post.getEscapedContent())}

and then in the domain object I escaped anything inside of the code blocks

/**
 * I will return the content of a post with the necessary html escaping. To render html in code blocks we
 * need to escape any html inside of <code></code>
 * @return String
 */
def getEscapedContent(){
    content.replaceAll(/(?ms)(<code.*?>)(.*?)(<\/code>)/) { it, open, code, close ->
        open + code.encodeAsHTML() + close
    }
}