Rails3 and safe nl2br !

前端 未结 3 1400
南笙
南笙 2021-02-04 05:33

I have a system for the users to be able to post comments.

The comments are grasped into a textarea.

My problem is to format the comments with br tag to replace

3条回答
  •  遇见更好的自我
    2021-02-04 06:30

    The best way I can figure to go about this is using the sanitize method to strip all but the BR tag we want.

    Assume that we have @var with the content "some\ntext":

    Trying <%= @var.gsub(/\n/, '
    ') %>
    doesn't work.

    Trying <%= h @var.gsub(/\n/, '
    ').html_safe %>
    doesn't work and is unsafe.

    Trying <%= sanitize(@var.gsub(/\n/, '
    '), :tags => %w(br) %>
    WORKS.

    I haven't tested this very well, but it allows the BR tag to work, and replaced a dummy script alert I added with white space, so it seems to be doing its job. If anyone else has an idea or can say if this is a safe solution, please do.

    Update:

    Another idea suggested by Jose Valim:

    <%= h(@var).gsub(/\n/, '
    ') %>
    Works

提交回复
热议问题