将Twitter共享按钮(包含JS和所有内容)嵌入到Mustache模板中

时间:2012-03-16 11:27:44

标签: javascript dom twitter mustache

如何将Twitter(带有JS和所有内容)共享按钮嵌入到Mustache模板中?

我遇到的问题是我的AJAX应用程序没有重新加载页面,只是根据Mustache模板切换视图。我注意到widjets.js提供的功能根本没有打开,因为JS文件每个应用程序生命周期只加载一次,并搜索DOM_READY上带有“twitter”标签的标签。但是,这完全排除了稍后从模板呈现HTML的情况。

我知道我可以使用原始超链接来推特并将其自定义为看起来像一个按钮,但这太过于原始。

2 个答案:

答案 0 :(得分:2)

这是一个在我的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>

答案 1 :(得分:0)

你可以不在document ready上调用init函数,而是从想要显示twitter按钮的视图中调用。

相关问题