2013-05-11 61 views
2

標記文本將字符串所以我有這個字符串:裏面視圖

"<p> Here it is: </p> <p> <a href="http://localhost:3000/" class="button">Open</a> </p>" 

在控制器內部生成此字符串,具體取決於幾個參數。

我希望能夠展示這個字符串在視圖中,解釋爲標記文本:

<div class="row"> 
    <div class="twelve columns panel"> 
    <%= @string_with_markup %> 
    </div> 
</div> 

但結果卻是,這並不奇怪,在顯示的字符串,如,所以它顯示了一個一堆標記文本在呈現的頁面中。 雖然render_to_string或yield方法,但它不工作,我想我錯過了一些東西。

附加信息:

整個目的是要表明由系統發送的電子郵件的正文。 電子郵件是使用ActionMailer生成的,當用戶想要查看發送給他的電子郵件時,控制器將調用ActionMailer的適當方法,並提取電子郵件的正文。我談到的那個string_with_markup其實就是class:Mail :: Body

謝謝!

回答

1

您可以標記該字符串(HTML)的安全在你的控制器(或助手):

@string_with_markup = '<p>Here it is ...</p>'.html_safe 

,並使其使用:

<%= @string_with_markup %> 

如果您不想在控制器中標記該字符串安全,請使用raw<%== [R比在你看來呼籲html_safe

<%= raw @string_with_markup %> 

到這相當於:

<%== @string_with_markup %> 

http://guides.rubyonrails.org/v3.2.9/active_support_core_extensions.html#output-safety

1

試試這個:

<div class="row"> 
    <div class="twelve columns panel"> 
    <%= @string_with_markup.html_safe %> 
    </div> 
</div> 
+0

快速的答案,但我會添加到它的解釋 - html_safe設置「字符串」爲HTML安全。這樣,您可以隨意從助手或模型返回HTML安全字符串。 – David 2013-05-11 18:09:11

+0

太棒了! 由於變量@string_with_markup是類Mail :: Body,我不得不打電話給: '@ string_with_markup.to_s.html_safe' 謝謝! – 2013-05-11 18:12:01