1

Storytime

In Play's templating scheme, I have this simplified setup:

@(param:String)    
<!DOCTYPE html>
<html>    <head><!-- JQuery & Bootstrap css+js includes --></head>    <body> 
    @param    
    <input type="text" data-provide="typeahead" data-source='@Html(param)' data-items="4">
</body>    </html>

The @Html() is mentioned here and the bottom of here and basically prevents characters like < from being replaced with &lt;. I'm attempting to pass in a Json.stringify-ed and Json.toJson-ed List[String] that I get from my database into the HTML through Play's template engine, and then have Bootstrap pick it up automatically from the data-source attribute.

Say @param evaluates to a JSON object that contains a string with a ':

<input data-provide="typeahead" data-source='["can't","hi","boom"]' data-items="4" type="text" >


I realized that the single quote characters needed to be escaped in my data-source JSON object. At first I experimented with using \ and even \\\ to no avail. I even set out to write a regex replacer for the task to emulate the addSlashes() mentioned here

Then on a whim...

<input data-provide="typeahead" data-source='["can&#x27;t","hi", "boom"]' data-items="4" type="text" >

Everything works normally now! (when the data-source is hardcoded. Still need to figure out how to unescape @Html() so that &#x27; doesn't disappear.)


Question

Why does Bootstrap Typeahead need to read in the data-source with the single-quote characters unescaped?





For posterity:

val quoteRegex = """'""".r
quoteRegex.replaceAllIn(str, m => "&#x27;")
Community
  • 1
  • 1
Meredith
  • 3,928
  • 4
  • 33
  • 58

1 Answers1

1

The problem with the single quotes is that it truncates your data-source attribute. The html parser is going to read your html and give you something like

<input data-provide="typeahead" data-source='["can' t","hi","boom"]' data-items="4" type="text" >

and your data-source attribute will have a value of ["can. So the problem isn't typeahead.

When you encode the single quote it no longer breaks the attribute and the encoded quote is added to the dom unencoded so you get the ' instead of &#x27;

Musa
  • 96,336
  • 17
  • 118
  • 137
  • Then how does `'` get parsed as a single quote character when it's read by the Typeahead plugin? Is this just how jQuery works? – Meredith Jun 14 '13 at 04:31
  • `'` get converted to `'`, html entities are converted to their equivalent characters – Musa Jun 14 '13 at 04:34
  • I guess jQuery just reads in html entities as their equivalent characters then o_o I think what I'm actually trying to grasp is "How does jQuery work" – Meredith Jun 14 '13 at 04:38