레일스에서 HTML 콘텐츠가있는 변수가있는 경우 뷰 파일에서 인코딩되지 않은 채 어떻게 출력합니까? 예를 들어레일스에서 변수를 어떻게 html_encode하지 않습니까?
이 코드 :
<% my_variable = "<b>Some Bolded Text</b>" %>
<%= my_variable %>
출력 :
<b>Some Bolded Text</b>
레일스에서 HTML 콘텐츠가있는 변수가있는 경우 뷰 파일에서 인코딩되지 않은 채 어떻게 출력합니까? 예를 들어레일스에서 변수를 어떻게 html_encode하지 않습니까?
이 코드 :
<% my_variable = "<b>Some Bolded Text</b>" %>
<%= my_variable %>
출력 :
<b>Some Bolded Text</b>
당신이 레일 3 베타를 사용하고 있습니까? Rails 2는 기본적으로 HTML에서 출력물을 이스케이프 처리하지 않지만 대개 h
헬퍼를 사용해야합니다. Nate의 게시물을 참조하십시오. Rails 3을 사용하는 경우 raw
도우미를 사용하거나 문자열을 html로 설정해야합니다. 예
<% my_variable = "<b>Some Bolded Text</b>" %>
<%= raw my_variable %>
또는
<% my_variable = "<b>Some Bolded Text</b>".html_safe %>
<%= my_variable %>
는 레일 버전을 확인하고 우리에게 돌아 가야.
ActionView::Helpers::TextHelper이 대신 태그를 탈출의, 그들을 완전히 제거하는 방법 strip_tags를 제공합니다.
소스 [참조] :
def strip_tags(html)
return html if html.blank?
if html.index("<")
text = ""
tokenizer = HTML::Tokenizer.new(html)
while token = tokenizer.next
node = HTML::Node.parse(nil, 0, 0, token, false)
# result is only the content of any Text nodes
text << node.to_s if node.class == HTML::Text
end
# strip any comments, and if they have a newline at the end (ie. line with
# only a comment) strip that too
text.gsub(/<!--(.*?)-->[\n]?/m, "")
else
html # already plain text
end
end
<%= strip_tags(my_variable) %>
감사 솔로하지만 HTML 태그가 손상되지 않도록하고 페이지에 렌더링하고 싶습니다. – deadkarma
감사합니다! 그거였다! 레일 3 Beta – deadkarma
"raw"키워드가 레일 4에서도 작동했습니다. – emery