0

In my database I have:

ListItem.title = Hello & Goodbye3 

Then in my view I have:

ko.mapping.updateFromJS(List.list_items_open, <%= raw @list.list_items.where(:completed => false).to_json(:only => [:id, :title, :completed, :position]) %> );

<ol data-bind='template: { name: "list_item_template", foreach: List.list_items_open}'></ol>

<script type="text/html" id="list_item_template">
  <li class="listItem">
     <input class="list_item_title" maxlength="250" name="list_item[title]" type="text" data-bind="value: title>
  </li>
</script>

Problem here is that the value in the input is being rendered as:

Hello &amp; Goodbye3

And not:

Hello & Goodbye3

Any ideas on how I should be handling this? Were I should be encoding as raw? Thanks

AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012

2 Answers2

2

If you have control over the content in the database, I would say don't encode text in the database. You should store your text as "Hello & Goodbye3".

See Should we HTML-encode special characters before storing them in the database? for more discussion.

Community
  • 1
  • 1
Mark Robinson
  • 13,128
  • 13
  • 63
  • 81
  • I agree unless the Title column is actually meant to be raw html (like you could add tags, ie. `Hello Goodbye` is a valid value). If its only meant to be text though, definitely don't pre-encode it. – Paul Tyng Nov 08 '11 at 16:19
0

If you don't have control over the content in the database you could use a dependentObservable which deals with the encoding and decoding:

<p data-bind="text:name"></p>
<input type="text" data-bind="value: nameConverted "></input>

var viewModel = {
    name: ko.observable('Hello &amp; Goodbye3')
};

viewModel.nameConverted = ko.dependentObservable({
    read: function() {
        return htmlDecode(this.name());
    },
    write: function(value) {
        this.name(htmlEncode(value));
    },
    owner: viewModel
});

function htmlEncode(value){ 
  return $('<div/>').text(value).html(); 
} 

function htmlDecode(value){ 
  return $('<div/>').html(value).text(); 
} 

ko.applyBindings(viewModel);

See http://jsfiddle.net/unklefolk/k8jYN/ for a working example.

Mark Robinson
  • 13,128
  • 13
  • 63
  • 81