mitchlloyd / ember-islands

Render Ember components anywhere on a server-rendered page to create "Islands of Richness"
MIT License
236 stars 24 forks source link

[Question] How to handle special-chars like single-quote? #34

Closed jonasbuechel closed 7 years ago

jonasbuechel commented 7 years ago

Is there an existing way to handle special chars like the single-quote? If I put "Sally's User" into your example, the data-attrs string is broken. Possible solution by backend is to encode the whole string. Is there a hook available in your extension to get in and decode the string?

A possible solution is to react on each component by 'didReceiveAttrs' hook ant put this action into a mixin. Or is there a general better way?

`<div data-component='user-profile' data-attrs='{"name": "Sally's User", "id": "4"}'>

Sally likes hiking in the wilderness

`

mitchlloyd commented 7 years ago

Wow great question. This is definitely something that needs to be documented and the current docs in the README are misleading.

In this exact case, you can HTML escape the single quote, assuming that the point of having this string is to put it into HTML.

<div data-component='user-profile' data-attrs='{"name": "Sally&apos;s User", "id": "4"}'>

Of course the onus is then on you to create some helper on your server to html escape the values of each key that might contain a single quote.

As you mentioned, the real solution is to HTML escape the entire string that you'll put into data-attrs. The Rails helper shown in the readme does the right thing:

content_tag(:div, '', data: { component: name, attrs: attrs.to_json })

It produces HTML output like this:

<div data-attrs="{&quot;hi&quot;:&quot;there&quot;}" data-component="my-component"></div>

When Ember Islands calls element.getAttribute('data-attrs') this escaped string becomes a valid JSON string. Apparently this is just a browser thing that works.

However I didn't even notice what content_tag was doing at first because the Chrome Dev tools makes it look like this is just magically working:

screen shot 2016-12-09 at 10 52 30 am

So I learned something here.

The short answer is "HTML escape your JSON string in your server code and Ember Islands will work", but I need to update the README with this issue in mind.

mitchlloyd commented 7 years ago

Closed via: https://github.com/mitchlloyd/ember-islands/commit/2c95504c76abec9ad5cc5de9ad23e80f632d1998

jonasbuechel commented 7 years ago

Thanks a lot! It works perfectly with html-escaped strings.