问题
I'm using rails form. In that form, I've a text_area. I want to show pre-filled data in text area of rails. The data is html content.
I tried following,
<% test_val= "<h1>Test Value</h1>" %>
<%= form.text_area(:myval, :value => test_val.html_safe, size: '30x10', :style => 'border: 10;') %>
myval
is my form variable. But instead of printing Test Value
in bold and bigger font in text area, t showed <h1>Test Value</h1>
. I want the content in HTML tag to be printed with HTML formatting. Is it possible? If yes, how do I achieve it?
p.s. I'm using ruby v1.9.3 & rails 3.1.0
回答1:
This is not possible in a textarea, this is not related to rails but to Html.
Instead you can use a div and set it with contenteditable =true
example:
<div contentEditable="true">content goes here </div>
If you are using javascript you can store the result in a variable like so:
var myvar = document.getElementById("divid").innerHTML
回答2:
You may want to use a wysiwyg editor. I suggest you to have a look at
https://github.com/Nerian/bootstrap-wysihtml5-rails
With simple_form you can simple use it as:
<%= f.input :content, as: :wysihtml5 %>
回答3:
As I said previously, you should probably use a contentEditable
unfortunately, you won't be able to use the rails existing helper to send the form, and have to use a little Javascript to build the form, I do not find the method really 'clean' but it works:
<html>
<head></head>
<body>
<form id="my_form" action="#" method="POST">
<div id="editable_div" contenteditable>
<h1>Editable HTML Content</h1>
</div>
<input type="submit" />
</form>
</body>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
var form = $("#my_form");
form.submit(function() {
console.log('submitted');
form.append($('<input/>', {
type: 'hidden',
name: 'html_content',
value: $("#editable_div").html()
}));
});
</script>
</html>
You should be able to adapt this code to your rails one quite easily.
来源:https://stackoverflow.com/questions/32176897/how-do-i-show-formatted-text-in-rails-text-area