ruby nl2br outside <code> ... </code>
I've been struggling on this thing for a week without being able to find what I'm looking for.
Here is what I'd like to do:
I'm setting up a wiki where I can post all my knowledge to (yes, I know a couple thin开发者_StackOverflow社区gs :p) but I can't render it the way I'd like to. The bodies of my posts are text fields. In order to render them the right way I run the following command:
@post.body.gsub("\n", "<br />")
I also have some tags with some code inside that looks like this < code> my code < /code>.
Here come's the issue. Every line between the < code> and < /code> tags are changed to
but it doesn'r render properly since I'm using a code render template.Therefore, I'd like to know if there is a way to change all \n to < br /> except for those between < code> and < /code>
Thank you everyone for reading this and helping me out.
PS: Please do not consider the spaces after the < in each tag. I had to do this to "espace" them.
Julien
simple_format
will replace your \n
to <br/>
and double \n\n
to <p></p>
http://apidock.com/rails/ActionView/Helpers/TextHelper/simple_format
And here is a helper method for your problem
def text_format(text)
reg = /(<code>[.|\W|\w]+<\/code>)/
text.split(reg).map{|t| t =~ reg ? t : t.gsub(/\n/, "<br />") }.join()
end
text = 'Hello pedro!
Here is my code:
<code>
def text_format(text)
reg = /(<code>[.|\W|\w]+<\/code>)/
text.split(reg).map{|t| t =~ reg ? t : t.gsub(/\n/, "<br />") }.join()
end
</code>
Good luck!'
text_format text
#=> "Hello pedro!<br /><br />Here is my code:<br /><br /><code>\n def text_format(text)\n reg = /(<code>[.|\\W|\\w]+<\\/code>)/\n text.split(reg).map{|t| t =~ reg ? t.gsub(/\\n/, "<br />") : t }.join()\n end\n</code><br /><br />Good luck!"
精彩评论