Assuming that the variable contains the URL, like this:
$(document).ready(function(){
$('#player').youTubeEmbed("<%=escape_javascript(@clip)%>");
});
(Sorry, missed the fact that the JavaScript was not in the same file as the HTML -- as well it shouldn't be!)
Assuuming the variable contains the URL, if you don't want the URL shown, you can embed it in a page variable like so (replace the div
code in show.html.erb with the following):
<script type='text/javascript'>
window.myStuff = {
clipUrl: "<%=escape_javascript(@clip)%>"
};
</script>
...(or
<script type='text/javascript'>
var myStuff = {
clipUrl: "<%=escape_javascript(@clip)%>"
};
</script>
...which is very nearly the same thing).
...and then you can use it like this:
$(document).ready(function(){
$('#player').youTubeEmbed(window.myStuff.clipUrl);
});
When outputting a variable's value in this way, you need to ensure that what gets written out ends up being valid JavaScript. So for instance, if the @clip
variable contains a "
or a \
, you'll need to ensure that the "
is turned into \"
and that any lone backslash is turned into \\
. Jakub Hampl helpfully pointed out the escape_javascript
function for this, which I've edited into the code examples.
Doing this that means we're putting a new symbol on window
. I made our new symbol an object so that if we need to do this with other things, we can include them in that same object so we don't end up with symbols all over the place (creating lots of global symbols — which is to so, window
properties — tends to become a maintenance issue, best avoided). So for instance, if you had two clips:
<script type='text/javascript'>
window.myStuff = {
someNiftyClip: "<%=escape_javascript(@clip)%>",
someOtherNiftyClip: "<%=escape_javascript(@anotherClip)%>"
};
</script>
Off-topic: In the line calling youTubeEmbed
, note I added a semicolon at the end. Best not to rely on JavaScript's semicolon insertion.