开发者

newline characters screwing up <pre> tags (Ruby on Rails)

开发者 https://www.devze.com 2023-02-21 16:40 出处:网络
I developing a blog and some really annoying stuff is happening with newline characters (\\n). Everything works fine except if I make a post that contains pre tags my newline characters screw up the i

I developing a blog and some really annoying stuff is happening with newline characters (\n). Everything works fine except if I make a post that contains pre tags my newline characters screw up the indentation.

So if I have code that looks like this

<pre>
  <code>
    some code some code
    more code more code
  </c开发者_如何转开发ode>
</pre>

For some reason the newline characters that are saved in the db field with the post are causing whatever is inside the pre tag to be indented by a tab or two.

I have no idea why it's doing it, but if I do something like

string.gsub!(/\n/, "<br />")

The indentation is removed, so I know it has to do with the \n. But then my problem is that there are way too many line breaks and the format is then way off.

So then I tried to capture everything inside the pre tags with a method that looks like this

def remove_newlines(string)
   regexp = /<pre>\s?(.*?)\s?<\/pre>/
   code = regexp.match(string)
   code[1].gsub!(/\n/, "<br />")
end

But I can't get that to work properly.

Anyone know how I can rid of this weird indentation problem, or any pointers on this?

Thanks!


It sounds like your template engine is auto-indenting the contents of the <pre> tags. Browsers render the whitespace inside <pre> tags as it is (and so they should, according to specs). This means that the whitespace at the beginning of each line inside the <pre> added by the template engine in order to make the HTML source more readable is rendered in the actual page as well, unlike whitespace most other places in HTML source.

The solution therefore depends on your templating language.

If you are using HAML:

HAML FAQ: How do I stop Haml from indenting the contents of my pre and textarea tags?

Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消