问题
Hello I'm new to meteor and programming in general.
I am trying to have my page load the JWPlayer video embed code dynamically from the database collection. Since I have over 100 videos being made for this app/site I figured this would be the easiest way. Please let me know if there is a better way to do this!!
The issue it seems is the javascript embed code from the database is loading before the page and as such is not getting executed. Here is my code.
Template code:
<template name="videos">
{{{viddiv}}}
<script type='text/javascript'>
{{{vidscrip}}}
</script>
</template>
The code from the database collection (it's been properly escaped so it's kinda crazy):
vids.insert ({
_id: "1",
viddiv: '<div id=\'player64I7ulrK\'><\/div>',
vidscrip: "jwplayer(\'player64I7ulrK\').setup({\r\n
playlist: \'\/\/jwpsrv.com\/feed\/64I7ulrK.rss\',\r\n
width: \'100%\',\r\n
aspectratio: \'16:9\'\r\n
});"
});
When I launch my app and view the page I can see that the everything is there and looks good. But the script isn't executing.
<div id="player64I7ulrK"></div>
<script type="text/javascript">
jwplayer('player64I7ulrK').setup({
playlist: '//jwpsrv.com/feed/64I7ulrK.rss',
width: '100%',
aspectratio: '16:9'
});
</script>
And here is the route I am using to render the view (correct terminology?).
Router.map(function() {
this.route('videos', {
path: '/videos/:_id',
data: function() {return vids.findOne(this.params._id); }
});
});
I've played with Template.videos.rendered
and added a separate js file with the embed code in it. This did work, however I'm not sure how to load the code into this js file dynamically form the database collection. Which means I would have to hard code each embed =(
Here is the link to my git repository if you would like to look at it! https://github.com/jacksonvoice/VCU.git
Any help would be great! I'm kind of stuck on this one and need some help!
Thank you in advance!
回答1:
Embedding js code in db as escaped string is bad idea as it is not easy to manage, change, use. Instead I would refactor your code a little bit:
vids.insert({
url:'//jwpsrv.com/feed/64I7ulrK.rss',
width:'100%',
aspectratio:'16:9',
divSelector:'64I7ulrK'
})
Videos.html:
<template name="videos">
<div class="{{divSelector}}"></div>
</template>
Videos.js :
Template.videos.rendered = function () {
jwplayer(this.data.divSelector).setup({
playlist : this.data.url,
width : this.data.width,
aspectratio : this.data.aspectratio
});
};
来源:https://stackoverflow.com/questions/24169135/loading-jwplayer-embed-code-from-database-collection-into-a-page-template-in-met