【问题标题】:Embedding a Twitter share button (with JS and everything) into a Mustache template将 Twitter 分享按钮(带有 JS 和所有内容)嵌入到 Mustache 模板中
【发布时间】:2012-10-17 05:25:52
【问题描述】:
如何将 Twitter(包含 JS 和所有内容)分享按钮嵌入到 Mustache 模板中?
我遇到的问题是我的 AJAX 应用程序没有重新加载页面,而只是根据 Mustache 模板切换视图。我注意到 widjets.js 提供的功能根本没有打开,因为 JS 文件在每个应用程序生命周期中只加载一次,并在 DOM_READY 上搜索用“twitter”标签装饰的标签。但是,这完全排除了稍后从模板呈现 HTML 的情况。
我知道我可以使用原始超链接到 twitter 并将其自定义为看起来像一个按钮,但这太原始了。
【问题讨论】:
标签:
javascript
dom
twitter
mustache
【解决方案1】:
这是一个在我的 HTML 文件中使用模板对我有用的解决方案:
social.js:
$(function() {
var socialFeeds = {
twitter: {
account: "your-twitter-account",
script: function() {
// twitter code goes here, minus the script tags
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
// in my case, I had to re-render the twitter button, see here:
// http://stackoverflow.com/a/6536108/805003
$.ajax({ url: 'http://platform.twitter.com/widgets.js', dataType: 'script', cache:true});
}
}
}
$.Mustache.addFromDom('social-template');
$('#social').mustache('social-template', socialFeeds);
}
index.html:
<script id="social-template" type="text/html">
<div id='social'>
<p>Twitter button:</p>
<a href="https://twitter.com/share" class="twitter-share-button" data-via="{{twitter.account}}">Tweet</a>
{{ twitter.script }}
</div>
</script>
【解决方案2】:
您可以不在document ready 上调用初始化函数,而是从您希望出现 twitter 按钮的视图中调用。